How to find out from code if my Android app runs on emulator or real device?

后端 未结 9 2240

I have read this stackoverflow thread already and I tried using the code given in that answer to find out if I run my code on the emulator or on a real device:



        
9条回答
  •  春和景丽
    2020-12-09 18:04

    As stated in this post, IMEI and IMSI are harcoded on the emulator:

    2325     { "+CIMI", OPERATOR_HOME_MCCMNC "000000000", NULL },   /* request internation subscriber identification number */
    2326     { "+CGSN", "000000000000000", NULL },   /* request model version */
    



    You can easily get the value using

    adb shell dumpsys iphonesubinfo
    

    So checking the device's IMEI using TelephonyManager.getDeviceId() should be sufficient to find out, whether you're on an emulator or a real device.


    To be absolutely sure, you might combine it with checking the model name as stated by various other posts.

    public static boolean isRunningOnEmulator(final Context inContext) {
    
        final TelephonyManager theTelephonyManager = (TelephonyManager)inContext.getSystemService(Context.TELEPHONY_SERVICE);
        final boolean hasEmulatorImei = theTelephonyManager.getDeviceId().equals("000000000000000");
        final boolean hasEmulatorModelName = Build.MODEL.contains("google_sdk")
                || Build.MODEL.contains("Emulator")
                || Build.MODEL.contains("Android SDK");
    
        return hasEmulatorImei || hasEmulatorModelName;
    }
    


    The downside to this approach is that you need a context to access this information and instantiating a TelephonyManager for every check.

提交回复
热议问题