我希望我的代码在模拟器上运行时与在设备上运行时略有不同。(例如,使用10.0.2.2代替公共URL在开发服务器上自动运行。)检测Android应用程序何时在模拟器中运行的最佳方法是什么?
当前回答
以下是我的解决方案(它只适用于在调试机器上运行web服务器): 我已经创建了一个后台任务,当应用程序启动时启动。它查找http://10.0.2.2,如果它存在,它将全局参数(IsDebug)更改为true。这是一种无声的方式来找出你在哪里跑步。
public class CheckDebugModeTask extends AsyncTask<String, Void, String> {
public static boolean IsDebug = false;
public CheckDebugModeTask()
{
}
@Override
protected String doInBackground(String... params) {
try {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 2000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
String url2 = "http://10.0.2.2";
HttpGet httpGet = new HttpGet(url2);
DefaultHttpClient client = new DefaultHttpClient(httpParameters);
HttpResponse response2 = client.execute(httpGet);
if (response2 == null || response2.getEntity() == null || response2.getEntity().getContent() == null)
return "";
return "Debug";
} catch (Exception e) {
return "";
}
}
@Override
protected void onPostExecute (String result)
{
if (result == "Debug")
{
CheckDebugModeTask.IsDebug = true;
}
}
从主活动onCreate:
CheckDebugModeTask checkDebugMode = new CheckDebugModeTask();
checkDebugMode.execute("");
其他回答
根据其他答案的提示,这可能是最可靠的方法:
isEmulator = "金鱼".equals(Build.HARDWARE)
以下两个都被设置为“google_sdk”:
Build.PRODUCT
Build.MODEL
因此,使用下列任意一行就足够了。
"google_sdk".equals(Build.MODEL)
or
"google_sdk".equals(Build.PRODUCT)
这个代码适用于我
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String networkOperator = tm.getNetworkOperatorName();
if("Android".equals(networkOperator)) {
// Emulator
}
else {
// Device
}
如果该设备没有sim卡,它将返回空字符串:""
由于Android模拟器总是返回“Android”作为网络运营商,我使用上面的代码。
另一种选择是查看ro。硬件属性,看看它是否设置为金鱼。不幸的是,在Java中似乎没有一个简单的方法来做到这一点,但在C中使用property_get()是很简单的。
我的建议:
试试github上的这个。
易于检测android模拟器
在设备场(https://aws.amazon.com/device-farm/)的真实设备上检查 BlueStacks Genymotion Android模拟器 安迪46.2.207.0 菜单玩 诺克斯应用播放器 Koplayer …
如何与示例一起使用:
EmulatorDetector.with(this)
.setCheckTelephony(true)
.addPackageName("com.bluestacks")
.setDebug(true)
.detect(new EmulatorDetector.OnEmulatorDetectorListener() {
@Override
public void onResult(boolean isEmulator) {
if(isEmulator){
// Do your work
}
else{
// Not emulator and do your work
}
}
});
推荐文章
- 我如何在一个片段中访问getSupportFragmentManager() ?
- 调试在哪里。Android Studio中的密钥存储库
- 从资产中读取文件
- 在不活动的地方调用getLayoutInflater()
- 设置Android布局元素的背景颜色
- 错误:'keytool'不能被识别为内部或外部命令、可操作程序或批处理文件
- 在应用程序本身中更改Locale
- apk (.apk)和应用程序包(.aab)的区别
- 如何设置超时在改造库?
- Android - SPAN_EXCLUSIVE_EXCLUSIVE跨度不能为零长度
- TextView的字体大小在Android应用程序改变字体大小从本机设置
- 如何模拟Android杀死我的进程
- 禁用EditText闪烁光标
- Android Eclipse -无法找到*.apk
- 设置TextView文本从html格式的字符串资源在XML