I have one Android open source library project in which I have been using a separate library for logging (Which is also developed by me).
The logging library is not that important, but it makes the development and debugging easier (Both for me and the user of the main library).
I am using gradle (and Jitpack) to use both the libraries. Now the Logging library is actually having few extra permissions in manifest (For writing logs to file, not necessary for the main library).
Now one of the user asked me to remove the extra permissions. And I don't know how can I do that without removing the logging library (or changing the functionality in the logging library itself).
I even realised that few people might not need the logging library at all, so is there a way I can make it optional, like if the user didn't include the Logging library in their build.gradle, it won't get imported which I can detect and not call the logging functions?
I know it sounds confusing, but I'd like to know how to decouple both the libraries. In fact please let me know if you know about any such example from any popular library too.
Yes you can probably do both with some clever tricks.
part 1. PERMISSIONS
About the manifest permissions. It's pretty simple, do not add the permission to the logging library and instead, check it on runtime. Like this:
if (context.checkPermission(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
android.os.Process.myPid(),
Process.myUid()) == PackageManager.PERMISSION_GRANTED) {
carry on with your write to disk operation ...
}
and then on your documentation you write that IF developers using the library wants to have a local logging, they have to declare WRITE_EXTERNAL_STORAGE on the manifest.
part 2. (not) IMPORTING THE LIB
All I'm gonna write here is by heart and 100% NOT tested. There might (will) be some errors that you'll have to shift around, but hopefully I'll pass a solid idea.
First on the NoobCameraFlash lib you'll define LumberJack in the build.gradle file with provided instead of compile. This will make the compiler known about the LumberJack so compilation can pass, but it won't include it on the actual build.
Then create in your NoobCameraFlash library a class that is a mirror of the library funcionalities. Which means the methods d(String, String), e(String, String) etc.
Then you in this mirror class you will something like the following to check if lumberjack is actually available.
private static boolean lumberJackAvailable = false;
private static boolean lumberJackTested = false;
private static boolean isLumberJackAvailable() {
if(lumberJackTested) return lumberJackAvailable;
lumberJackTested = true;
try {
if(Class.forName("") != null) {
lumberJackAvailable = true;
}
} catch(Throwable e){
// ClassNotFoundException, LinkageError, ExceptionInInitializerError
}
return lumberJackAvailable;
}
public static LumberJackMirror create() {
// could also be a singleton
if(isLumberJackAvailable() return new LumberJackMirror();
else return null;
}
then of course you have to check if(lumberJackMirror != null). So as you can see it's not the most straight forward way of doing things.
Another way that simplifies this a little bit is to create an interface in a different library, that both the mirror and the actual LumberJack implements and use the factory can return an empty implementation of the interface instead of having to null check all the time.
As well, include on the documentation, that if developers want to have the logging functionality they have to add it to the build.gradle. Something like compile 'your_groud_id:lumberjack:version'
edit
another common way of doing that is to make it explicit on the NoobCameraFlash initialisation code. Something like:
NoobCameraFlash.config()
.setLogger(new LumberJack());
so that forces developers to know about LumberJack instead of checking via Class. But that would mean you need some version of LumberJack that is not just static methods.
end_edit
But hopefully just the permission removal will be enough and you don't have to do this part.2 =]
happy coding.
Related
We are building an Android application where we use Timber for Log-output. We have defined our own .e, .d, .v etc functions and use if (BuildConfig.DEBUG) to see if we should output the log. This takes care of the issue that we don't want to output Debug-logs in our releases but all the string literals used in our functions calls are still present in the compiled source code. We furthermore use ProGuard for obfuscation. To exemplify, in a class we can have:
somObj.normalFunction(variable)
Log.d("This secret class achieved its secret mission!");
In our release, this will not be seen in the app logs but if you reverse-engineer the APK you will see something like:
q.b(m)
z.a("This secret class achieved its secret mission!");
which can give a hint to the hackers about what class they are looking at.
So what we're looking for is to either be able to completely REMOVE all the Log function calls at compile time (using some pre-processing, annotation or something, but hopefully without having to add something before EVERY function call) OR to obfuscate all the String literal parameters to those function calls. So, two ideal solutions would be if the source, just before compilation, instead looks like:
q.b(m);
or
q.b(m);
z.a("jgasoisamgp23mmwaföfm,ak,ä")
Just by thinking I can see two bad ways to achieve this. Either we surround ALL calls to Log.d with if(BuildConfig.DEBUG) which will make the compiler remove them before compilation. But this is very tideous. OR, we make sure that every time you want to add a log-printout you need to do
Log.d(LogClass.getLog(1234))
and you then define ALL those logs inside LogClass and then remove them with if(BuildConfig.DEBUG) and return null in getLog if that's the case. But that makes it more tideous every time you want to add a log.
So finally, is there any GOOD solution to this?
DISCLAIMER: I work for PreEmptive, the company that makes PreEmptive Protection - DashO.
DashO is capable of removing calls to specific methods (e.g., Log methods). While this doesn't remove the instructions to load the string literal, just the call itself, DashO also offers String Encryption, which would offer some protection to those string literals.
As an example, I ran this class through DashO:
public class App {
public static void main(String[] args) {
Log.d("Secret message here");
}
}
After removing calls to Log.d with String Encryption on, the decompiled output looks like this:
public class App
{
public static void main(String[] paramArrayOfString)
{
a.replace("Bwpfpb7u|ih}z{?($0&", -12 - -61);
}
}
DashO offers other protections (e.g., Control Flow Obfuscation) that tend to break decompilers; I've turned those off for this demonstration.
What I would do is one or some of the following:
Use Timber (so you don't need to bother removing things or adding if statements). You simply do this once in your Application#onCreate(); if you are in DEBUG, then you plant a DebugTree that prints to the console. Else, you plant an "empty tree" that does nothing.
Simulate Timber but create your own "YourLogger" class and do the same (if you don't want to include a "third-party" library even though it's just one class). So you'd have YourLogger.v("tag", "string") and inside you'd do: if (debug) { Log.v(tag, string); } and so on and so forth for all other log types.
Use Proguard to strip the logging, and what not.
1 and 2 imply you go through your app and replace all Log. lines with either Timber. or YourLogger.
Option 3 wouldn't need that, since the code would be removed during obfuscation and the calls would do nothing, but this is mode complicated (and I haven't done it in years, don't even remember how it's done, probably easy to look it up).
I'd go for 1.
Update
Since apparently I don't know how to read, I think that in order to achieve this, your only bet is to have some sort of lookup mechanism for the actual text you want to emit/hide.
Strings.xml is the easiest, since it's included with Android and you can even localize the error messages (if that were needed, of course). Yes, there's a lookup time penalty, but I'd say unless you're iterating over thousands of items and logging different strings every time or something, the penalty wont' be noticeable (I don't have data for this, you'd have to benchmark).
Alternatively, instead of relying on resources, you could just use a file, read it, and load the strings in memory... a trade off; do you use more memory at the cost of simplicity and time to code the solution, or do you use the built-in mechanism and pay the CPU time?
I'm still fairly new to the programming world in general, so I hope this isn't an obvious/abstract question.
I'm developing an android library that needs to monitor the lifecycle events of the activity that's using it. How do I accomplish this while creating the least amount of work for the developer using my library? Preferably, I like to use something that is already built into Android.
I've seen similar questions, such as: Automatically log Android lifecycle events using ActivityLifecycleCallbacks?
But it doesn't really apply to a library project.
Am I missing something? Any insight would be greatly appreciated.
I think that your best (long term) option is to have a setup along with the integration of the library (i.e. pass the Application in an entry point of your library).
That said, there is an undocumented way to get the current Application. as described here: https://stackoverflow.com/a/12495865/458365
try {
final Class<?> activityThreadClass =
Class.forName("android.app.ActivityThread");
final Method method =
activityThreadClass.getMethod("currentApplication");
return (Application) method.invoke(null, (Object[]) null);
} catch (final Exception e) {
// handle exception
}
Once you have that you can call Application.registerActivityLifecycleCallbacks() to register your own ActivityLifecycleCallbacks
Update:
Another alternative to get the application (Context) that I've come across is to use a Content provider. I think libraries like Firebase use this method because it has zero set up. However, it requires the consumer of the library to have an application object (which actually is the same as with the manual method) but it does look a lot cleaner:
Inside the onCreate of the CP we can cast getContext as Application and go from there with the Callbacks process.
Source: https://medium.com/#andretietz/auto-initialize-your-android-library-2349daf06920
In C-derivative languages there is the possibility to have conditional code for debug and runtime. That way there is no overhead left in the runtime.
How would I do this with Java/Android and the Log.i statements? If I just use a constant global boolean debugOn that obviously leaves the redundant checks in the runtime.
What is the best approach for conditional Log-statements?
Many thanks
EDIT:
Since there are quite some comments following the accepted answer I post my conclusion here....
private static final boolean DEBUG = true;
if (DEBUG) Log.i("xxx",this.getClass().getName()+ "->" + Thread.currentThread().getStackTrace()[2].getMethodName() );
...just like in xCode :)
Android build system started providing a constant BuildConfig.DEBUG some time ago, so I suggest using it and writing the code like this:
if (BuildConfig.DEBUG) Log.i(TAG, "Message");
No redundant checks will be made since it's a constant. This code will be optimized even by compiler, but you also have ProGuard at your disposal. Even if the checks are in place, any possible impact on performance should be negligible.
This approach used to have one drawback that you had to edit this constant yourself, either manually or through a custom rule in the build file. Now, however, this is handled automatically by the build system, so you don't have to do anything yourself.
Create your own Log class by by extending Log class , create static variable debugLevel inside it , create your own methods and labels like INFO, DEBUG ect .
now change in value of static varable debugLevel , will reflect to whole application.
so no need for if(debug) everywhere .
Java doesn't have C-like conditional compilation, unless you implement it yourself. (It's not all that difficult, but IMO it's not worth the trouble.)
Your options are pretty limited. The best you can do is wrap expensive logging statements in an isLoggable.
if (Log.isLoggable(tag, Log.DEBUG)) {
Log.d(tag, expensiveStringGeneration());
}
For short log statements, it's more noise than it's worth.
Edit Malcolm might be right (although I still wouldn't bother, in all likelihood.)
Edit The comparison to a static DEBUG is still in the byte code; ProGuard should remove it the unnecessary branch. Without ProGuard, it would be up to the JIT, or the compiler implementation.
Since Android introduced library projects, I've been converting my app into a library so that I can make several versions with appropriate tweaks (for example, a free and pro version using the same code base, but changing a few things).
I initially had trouble allowing the library project's code access to fields in my sub-projects. In other words, my free and pro versions each had a class with a few constants in them, which the library project would use to distinguish certain features.
In the sub-project, I extended the library's main activity and added a static initialisation block which uses reflection to change the values of fields in the library.
public class MyMainActivityProVersion extends MyMainActivity {
public static final String TAG = Constants.APP_NAME + "/SubClass";
static {
try {
ConstantsHelper.setConstants(Constants.class);
} catch (Exception e) {
Log.d(TAG, "--- Constants not initialised! ---");
e.printStackTrace();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
In this code, ConstantsHelper is in the library, and I am providing Constants.class from my sub-project. This initialises the constants in the library project.
My approach works great, except for one particular use case. When the app hasn't been used in a while and it is 'stopped' by the OS, the static fields in ConstantsHelper are forgotten.
The constants are supposed to be reset by the main activity (as shown above), but the main activity isn't even launched because the OS resumes a different activity. The result of this is that the initialisation of the constants is forgotten and I cannot re-initialise them because the resumed activity is in the library (which has no knowledge of the sub-project).
How can I 'tell' other activities in the library to call code from sub-projects on resuming? Alternatively, is there a way to ensure that some code in my sub-project is called on every resume?
I think you're "cheating" by trying to share data across two Activities through static members. This happens to work when they're in the same, or related, classloaders. Here I believe Android uses separate classloaders for separate Activities, but, child Activities are in child classloaders. So ViewActivity happens to be able to see up into the parent classloader and see statics for the parent. Later I believe that parent goes away, and so your child re-loads MyMainActivity locally when you next access it and it's not initialized as you wanted. (Well, if it's not that, it's something very like this explanation.)
I think there are some more robust alternatives. You could use the LicenseChecker API to decide whether you're in a free or for-pay version rather than rely on details of the activity lifecycle and classloader. That's probably going to be better as it protects you from other types of unauthorized use.
I'm afraid I never found a good answer to this question. I'll probably continue with my terrible use of reflection and figure out some hacky workaround.
I felt I should come back and at least point out that I didn't solve this for the benefit of others who come to this page.
You can resolve this using Android resources.
Basically, define your constants in a resources xml values file in your Library project
E.g. "lib project"\values\constants.xml
<resources xmlns:tools="http://schemas.android.com/tools">
<bool name="const_free_version">false</bool>
<string name="const_a_constant">pippo</bool>
</resources>
Then, in your sub-project you can redefine the lib-project values using a different resources xml values file:
E.g. "sub project"\values\constants.xml
<resources xmlns:tools="http://schemas.android.com/tools">
<bool name="const_free_version">true</bool>
</resources>
In your lib project code when you refer to R.bool.const_free_version you get the actual value based on sub-project constant values xml.
Note that you don't have to redefine every values defined in the lib project constants.xml but only the ones you need different in your sub project.
I am writing my first Android application and I am liberally using asserts() from junit.framework.Assert
I would like to find a way to ensure that the asserts are only compiled into the debug build, not in the release build.
I know how to query the android:debuggable attribute from the manifest so I could create a variable and accomplish this in the following fashon:
static final boolean mDebug = ...
if (mDebug)
Assert.assertNotNull(view);
Is there a better way to do this? i.e. I would prefer not to use an if() with each assert.
thanks
I think the Java language's assert keyword is likely what you want. Under the covers, the assert keyword essentially compiles into Dalvik byte code that does two things:
Checks whether the static variable assertionsDisabled (set in the class' static constructor via a call to java.lang.Class.desiredAssertionStatus()) is != 0 and if so, does nothing
If it is 0, then it checks the assertion expression and throws a java.lang.AssertionError if the expression resolves to false, effectively terminating your application.
The Dalvik runtime by default has assertions turned off, and therefore desiredAssertionStatus always returns 1 (or more precisely, some non-zero value). This is akin to running in "retail" mode. In order to turn on "debug" mode, you can run the following command against the emulator or the device:
adb shell setprop debug.assert 1
and this should do the trick (should work on the emulator or any rooted debugging-ready device).
Note however that the aforementioned Dalvik code that checks the value of assertionsDisabled and throws an AssertionError if the expression is false is always included in your byte code and liberal sprinkling of asserts in your code may lead to byte code bloat.
Please see this for a bit more detail: Can I use assert on Android devices?
If you're concerned about shipping code with the JUnit asserts in (or any other class path), you can use the ProGuard config option 'assumenosideeffects', which will strip out a class path on the assumption that removing it does nothing to the code.
Eg.
-assumenosideeffects class junit.framework.Assert {
*;
}
I have a common debug library I put all my testing methods in, and then use this option to strip it from my released apps.
This also removes the hard to spot problem of strings being manipulated that are never used in release code. For example if you write a debug log method, and in that method you check for debug mode before logging the string, you are still constructing the string, allocating memory, calling the method, but then opting to do nothing. Stripping the class out then removes the calls entirely, meaning as long as your string is constructed inside the method call, it goes away as well.
Make sure it is genuinely safe to just strip the lines out however, as it is done with no checking on ProGuard's part. Removing any void returning method will be fine, however if you are taking any return values from whatever you are removing, make sure you aren't using them for actual operational logic.
I mean if you were using a language feature, like assert(), the compiler should be able to strip that out. But this is an actual class and if a class is referenced by executable code it will be included or assumed included in the final product by the compiler.
However there is nothing stopping you from creating a script that removes all the references to the Assert class in all of your code base before compilation.
Another approach would be to make a test project that targets your application and within JUnit tests actually calls the Assert on the areas which you want to make sure work. I personally like this approach because it is a nice and clean separation of test and application.
If you are just worried about the having an if-statement everywhere, then just wrap Assert with your own class, DebuggableAssert which does that check before each call to Assert.X. It will be sort of less performant because of the method entry/exit and the conditionals but if you can maintain your code better then it might be worth it.