How can I detect when an Android application is running in the emulator?

前端 未结 30 2842
无人及你
无人及你 2020-11-22 16:42

I would like to have my code run slightly differently when running on the emulator than when running on a device. (For example, using 10.0.2.2 instead of a

30条回答
  •  青春惊慌失措
    2020-11-22 17:20

    Another option is to check if you are in debug mode or production mode:

    if (BuildConfig.DEBUG) { Log.i(TAG, "I am in debug mode"); }

    simple and reliable.

    Not totally the answer of the question but in most cases you may want to distinguish between debugging/test sessions and life sessions of your user base.

    In my case I set google analytics to dryRun() when in debug mode so this approach works totally fine for me.


    For more advanced users there is another option. gradle build variants:

    in your app's gradle file add a new variant:

    buildTypes {
        release {
            // some already existing commands
        }
        debug {
            // some already existing commands
        }
        // the following is new
        test {
        }
    }
    

    In your code check the build type:

    if ("test".equals(BuildConfig.BUILD_TYPE)) { Log.i(TAG, "I am in Test build type"); }
     else if ("debug".equals(BuildConfig.BUILD_TYPE)) { Log.i(TAG, "I am in Debug build type"); }
    

    Now you have the opportunity to build 3 different types of your app.

提交回复
热议问题