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


当前回答

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

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;

} 

其他回答

在模拟器的文件系统中放入一个文件;由于该文件不会存在于真正的设备上,这应该是稳定的,可靠的,容易修复当它崩溃。

不知道是否有更好的方法来检测emu,但模拟器将在根目录下有init.金鱼.rc文件。

它是特定于模拟器的启动脚本,在非模拟器构建中不应该出现。

这个代码适用于我

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String networkOperator = tm.getNetworkOperatorName();
if("Android".equals(networkOperator)) {
    // Emulator
}
else {
    // Device
}

如果该设备没有sim卡,它将返回空字符串:""

由于Android模拟器总是返回“Android”作为网络运营商,我使用上面的代码。

检查设备是否安装了这些包是一个好主意:

    mListPackageName.add("com.google.android.launcher.layouts.genymotion");
    mListPackageName.add("com.bluestacks");
    mListPackageName.add("com.vphone.launcher");
    mListPackageName.add("com.bignox.app");

我只是把它放在一个数组列表中…

然后简单地检查包管理器,直到找到一个。

private static boolean isEmulByPackage(Context context) {
        final PackageManager pm = context.getPackageManager();
        for (final String pkgName : mListPackageName) {
            return isPackageInstalled(pkgName, pm);
        }
        return false;
    }

private static boolean isPackageInstalled(final String packageName, final PackageManager packageManager) {
    try {
        packageManager.getPackageInfo(packageName, 0);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
        return false;
    }
}

请注意,VM很可能有一些方法来欺骗应用程序,在这种情况下,可能有必要查看一些虚拟设备中不存在的物理传感器。

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

Build.PRODUCT
Build.MODEL

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

"google_sdk".equals(Build.MODEL)

or

"google_sdk".equals(Build.PRODUCT)