0

Is the value of BuildConfig.DEBUG general or related to my lib?

More info: I'm developing a lib/sdk, this sdk is built and deployed in a repository. The final app includes this deployed sdk.

Question: Is it possible to read the BuildConfig.DEBUG (true/false) value of the final app from the lib/sdk?

Dod: In my lib I have to enable something only if the final app is running in debug mode.

Giovesoft
  • 580
  • 6
  • 21
  • Consider to make some initialization of your lib in application class to set that lib exact status of your current app, debug/prod. Smth like: MyLib.isDebug(BuildConfig.DEBUG) – Алексей Юр Sep 18 '19 at 15:08

1 Answers1

1

Try this and let me know.

private static Boolean sDebug;

/**
 * Is {@link BuildConfig#DEBUG} still broken for library projects? If so, use this.</p>
 * 
 * See: https://code.google.com/p/android/issues/detail?id=52962</p>
 * 
 * @return {@code true} if this is a debug build, {@code false} if it is a production build.
 */
public static boolean isDebugBuild() {
    if (sDebug == null) {
        try {
            final Class<?> activityThread = Class.forName("android.app.ActivityThread");
            final Method currentPackage = activityThread.getMethod("currentPackageName");
            final String packageName = (String) currentPackage.invoke(null, (Object[]) null);
            final Class<?> buildConfig = Class.forName(packageName + ".BuildConfig");
            final Field DEBUG = buildConfig.getField("DEBUG");
            DEBUG.setAccessible(true);
            sDebug = DEBUG.getBoolean(null);
        } catch (final Throwable t) {
            final String message = t.getMessage();
            if (message != null && message.contains("BuildConfig")) {
                // Proguard obfuscated build. Most likely a production build.
                sDebug = false;
            } else {
                sDebug = BuildConfig.DEBUG;
            }
        }
    }
    return sDebug;
}
Sunny
  • 14,522
  • 15
  • 84
  • 129
  • It works ( @Sunny ) but if in the app gradle there is an `applicationIdSuffix` then the `Class.forName(packageName + ".BuildConfig");` will throw an exception: For example: `applianceId=com.giovesoft.app` `applicationIdSuffix=.ciao` the `packageName` variable will be `com.giovesoft.app.ciao` and the `Class.forName(packageName + ".BuildConfig")` will throw the exception. The correct one is `Class.forName("com.giovesoft.app.BuildConfig")` and not `Class.forName("com.giovesoft.app.ciao.BuildConfig")` – Giovesoft Sep 19 '19 at 12:18