HelloCW
HelloCW

Reputation: 2255

How can I know an App is running under debug model in Android Studio?

In Android Studio, I can click "Run" button in IDE to run an app, the app is running under debug model, but how can I know there is a debug model programatically? just like the following code.

If (IsDebug()){
   Toast.makeText(getApplicationContext(), "This is in debug, it will diplay some prompt information",Toast.LENGTH_LONG).show();
}else{
   Toast.makeText(getApplicationContext(), "This is release edition, it will not diplay debug information",Toast.LENGTH_LONG).show();
}

Upvotes: 1

Views: 104

Answers (4)

John Thur
John Thur

Reputation: 21

For simplicity, you can use BuildConfig such as if (BuildConfig.DEBUG) {...}.

BuildConfig is generated in compile time when you click 'Run' in AndroidStudio, which looks like:

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String APPLICATION_ID = "YOUR APP";
  public static final String BUILD_TYPE = "debug";
  public static final String FLAVOR = "";
  public static final int VERSION_CODE = 1;
  public static final String VERSION_NAME = "YOUR VERSION";
}

But some bugs are reported if you're using this in your library project. http://www.digipom.com/be-careful-with-buildconfig-debug/

If you want a more advanced way, you can define in your build.gradle. Enhancing your BuildConfig in http://toastdroid.com/2014/03/28/customizing-your-build-with-gradle/

Upvotes: 2

JDurstberger
JDurstberger

Reputation: 4255

It is possible to add BuildConfig-Variables to the Gradle-script and read them in the Code.

buildTypes {
    release {
        ...
        buildConfigField "int", "appMode", "0"
    }

    debug {
        ...
        buildConfigField "int", "appMode", "1"
    }
}

Read the variable like this:

If (BuildConfig.appMode == 1){
   Toast.makeText(getApplicationContext(), "This is in debug, it will diplay some prompt information",Toast.LENGTH_LONG).show();
}else{
   Toast.makeText(getApplicationContext(), "This is release edition, it will not diplay debug information",Toast.LENGTH_LONG).show();
}

Upvotes: 1

Mohammad Arman
Mohammad Arman

Reputation: 7065

Try this:

boolean isDebuggable =  ( 0 != ( getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE ) );

Upvotes: 0

Fahim
Fahim

Reputation: 12358

Use this to check if the app is debuggable or not

private boolean isDebuggable(Context ctx)
{
    boolean debuggable = false;

    PackageManager pm = ctx.getPackageManager();
    try
    {
        ApplicationInfo appinfo = pm.getApplicationInfo(ctx.getPackageName(), 0);
        debuggable = (0 != (appinfo.flags & ApplicationInfo.FLAG_DEBUGGABLE));
    }
    catch(NameNotFoundException e)
    {
        /*debuggable variable will remain false*/
    }

    return debuggable;
}

Upvotes: 0

Related Questions