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

前端 未结 30 2691
无人及你
无人及你 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:32

    How about something like the code below to tell if your app was signed with the debug key? it's not detecting the emulator but it might work for your purpose?

    public void onCreate Bundle b ) {
       super.onCreate(savedInstanceState);
       if ( signedWithDebugKey(this,this.getClass()) ) {
         blah blah blah
       }
    
      blah 
        blah 
          blah
    
    }
    
    static final String DEBUGKEY = 
          "get the debug key from logcat after calling the function below once from the emulator";    
    
    
    public static boolean signedWithDebugKey(Context context, Class cls) 
    {
        boolean result = false;
        try {
            ComponentName comp = new ComponentName(context, cls);
            PackageInfo pinfo = context.getPackageManager().getPackageInfo(comp.getPackageName(),PackageManager.GET_SIGNATURES);
            Signature sigs[] = pinfo.signatures;
            for ( int i = 0; i < sigs.length;i++)
            Log.d(TAG,sigs[i].toCharsString());
            if (DEBUGKEY.equals(sigs[0].toCharsString())) {
                result = true;
                Log.d(TAG,"package has been signed with the debug key");
            } else {
                Log.d(TAG,"package signed with a key other than the debug key");
            }
    
        } catch (android.content.pm.PackageManager.NameNotFoundException e) {
            return false;
        }
    
        return result;
    
    } 
    

提交回复
热议问题