Best way to Enable Android Support Library Debugging Flag - android

I'm running into many problems with the Android Support Library's ViewPager widget. Due to lack of documentation and just incorrect behavior, I've been learning how things work based on the source.
Looking at the source, I see that the ViewPager, I see a constant defined as
private static final boolean DEBUG = false;
If I can set this to true, then I can enable all the debugging for the ViewPager class
However, I can't determine how to modify this value at runtime. Reflection didn't seem to have access to it.
Is the only way to change this flag is by recompiling the source?

1.remove the "final" property;
2.add a method allowed to modify the DEBUG value;
3.recompile the source.

For enabling debug, maybe you should extends this class firstly. Then use your customized class instead of ViewPager.

A final variable cannot be changed after it is assigned therefore you would need to recompile from source with DEBUG = true if you want to enable the built in debugging statements.

Related

Handling dependencies in Library projects

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.

Detect whether you are ProGuarded at runtime?

Is there a way to detect (during runtime) if your application is ProGuarded? My goal here is to set a boolean value based on whether the application is ProGuarded or not.
I think it'd be easier if you set a boolean on build variants/flavors that you run ProGuard on.
For example: if you run ProGuard on Release and Staging but not on Debug, set a boolean variable to true on release and staging, but false on debug. This may help
This is a bit of a workaround but there are a few avenues by which reflection will solve this.
One way would be for you to first determine a class that is obfuscated/minified in the case of proguard. So say you have a class com.package.Thing that when proguard is enabled gets minified to be called just com.package.a (or whatever, it doesn't matter). Then use reflection to see if the original class exists.
Something like this:
boolean isProguardEnabled() {
try{
return Class.forName("com.package.Thing") == null;
catch(ClassNotFoundException cnfe) {
return true;
}
}
Obviously this only works if you know of a class that will be changed when proguard is enabled.
Perhaps more generically, you could look for a class com.package.a and use that as a signal that proguard is enabled, assuming of course that you don't genuinely have a class by the name of a. By default proguard will just use the alphabet to come up with class names, but you can also specify in your proguard configuration your own list of class names to use (which presents another way to do this same trick, look for one of those class names that you've specified).

efficient way to put debug/log statements in code - so they do not influence runtime

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.

Config.LOGD is deprecated

In android.util.Config, the Config.LOGD, Config.LOGV are now deprecated. Can you please tell me how to refactor my code to in order to get rid of the warnings compiler generated?
Thank you.
Config.DEBUG is deprecated use BuildConfig.DEBUG instead.
See the Google I/O App for Android (iosched) source code for reference on how to make logging more consistent throughout your Android application.
http://code.google.com/p/iosched/source/browse/android/src/com/google/android/apps/iosched/util/LogUtils.java
You should use Config.DEBUG(true in Debug mode) instead of Config.LOGD.
Yes, Robby means it. See the explanation of open source code.
public final class Config
{
/**
* If this is a debug build, this field will be true.
*/
public static final boolean DEBUG = ConfigBuildFlags.DEBUG;
PS: I just want to set the above words as comment, but I don't know how to set as comments, so I can only set as another answer.

better way to do Debug only assert code

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.

Categories

Resources