Write an interface that mimics the android Log interface
public interface LogInterface {
int ASSERT = 7;
int ERROR = 6;
int WARN = 5;
int INFO = 4;
int DEBUG = 3;
int VERBOSE = 2;
int d(String tag, String msg, Throwable tr)
int d(String tag, String msg)
int e(String tag, String msg)
int e(String tag, String msg, Throwable tr)
String getStackTraceString(Throwable tr)
...
Modify your main activity so that it implements LogInterface and add the implementation methods for the LogInterface
class MainActivity : AppCompatActivity() implements LogInterface {
public d(d(String tag, String msg, Throwable tr) {
return Log.d(tag,msg,tr);
}
public d(d(String tag, String msg) {
return Log.d(tag,msg);
}
public e(d(String tag, String msg, Throwable tr) {
return Log.e(tag,msg,tr);
}
public e(d(String tag, String msg) {
return Log.e(tag,msg);
}
public String getStackTraceString(Throwable tr) {
return Log.getStackTraceString(tr)
}
....
Write your own Log accessor class probably storing it in its own java library module:
final public class Log {
private Log() {} // prevent this class from being instantiated
static private LogInterface logInterface;
static protected void setLogInterface(LogInterface implementation) {
logInterface = implementation;
}
static public int ASSERT = LogInterface.ASSERT;
static public int ERROR = LogInterface.ERROR;
static public int WARN = LogInterface.WARN;
static public int INFO = LogInterface.INFO;
static public int DEBUG = LogInterface.DEBUG;
static public int VERBOSE = LogInterface.VERBOSE;
static d(String tag, String msg, Throwable tr) {
logInterface.d(tag,msg,tr);
}
...
Initialize the static class in your MainActivity's onCreate method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
Log.setLogInterface(this)
...
}
Include the module containing Log class as a dependencies in your java library. Then in your java library you can use a statement like:
Log.d("myJavaLibrary", "here's a debug message");
lazyDen's solution is fairly clever, I think it works and it involves less core writing. I don't however like the concept of calling android methods
directly from inside a Java library. The android.jar is code that is written to run on top of a properly configured android environment. When you start using
android methods from inside your java code, you have no guarantees that your android environment is properly setup when you use methods. Probably is,
but who knows for sure. In using the approach that I suggested you don't have to worry whether this is a issue or not. I would strongly suggest avoiding
Karim's suggestion of adding the android.jar as a dependency to the java library. That seems like asking for problems.