我希望我的代码在模拟器上运行时与在设备上运行时略有不同。(例如,使用10.0.2.2代替公共URL在开发服务器上自动运行。)检测Android应用程序何时在模拟器中运行的最佳方法是什么?


当前回答

一个常见的是Build.FINGERPRINT.contains("generic")

其他回答

用下面的代码来判断你的应用是否使用了调试键?它没有检测模拟器,但它可能为您的目的工作?

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;

} 

以下两个都被设置为“google_sdk”:

Build.PRODUCT
Build.MODEL

因此,使用下列任意一行就足够了。

"google_sdk".equals(Build.MODEL)

or

"google_sdk".equals(Build.PRODUCT)

最常用的方法是从品牌、名称……等。但是这个方法是静态的,并且适用于模拟器的有限版本。如果有1000多家虚拟机制造商呢?那么你必须写一段代码来匹配1000多个虚拟机?

但这是浪费时间。甚至在一段时间后,会有新的vm启动,你的脚本也会被浪费。

根据我的测试,我知道了 getRadioVersion()在虚拟机上返回空, 并返回版本号在真正的android设备。

public Boolean IsVM() 
{
    return android.os.Build.getRadioVersion().length() == 0;
} 
//return true if VM
//return false if real

虽然有用,但我没有官方解释。

代码:http://github.com/Back-X/anti-vm/blob/main/android/anti-vm.b4a

发布:http://github.com/Back-X/anti-vm/releases/download/1/anti-vm.apk

试试这个方法。

在谷歌和Genymotion模拟器上测试。

public Boolean IsVM() {
    String radioVersion = android.os.Build.getRadioVersion();
    return radioVersion == null || radioVersion.isEmpty() || radioVersion.equals("1.0.0.0");
}

检查答案,当使用LeapDroid, Droid4x或Andy模拟器时,没有一个可以工作,

适用于所有情况的方法如下:

 private static String getSystemProperty(String name) throws Exception {
    Class systemPropertyClazz = Class.forName("android.os.SystemProperties");
    return (String) systemPropertyClazz.getMethod("get", new Class[]{String.class}).invoke(systemPropertyClazz, new Object[]{name});
}

public boolean isEmulator() {
    boolean goldfish = getSystemProperty("ro.hardware").contains("goldfish");
    boolean emu = getSystemProperty("ro.kernel.qemu").length() > 0;
    boolean sdk = getSystemProperty("ro.product.model").equals("sdk");
    return goldfish || emu || sdk;
}