某些 Android 应用出于安全考虑,不允许运行在模拟器中,所以需要在应用启动时做检测,如果应用运行在模拟器中,则给出提示或者直接退出应用。
模拟器检测代码如下:
注:isTrulyDevice()方法返回 false则设备为模拟器。
/**
* 真实设备检测
*
* @return true:真机,false:模拟器
*/
public final static boolean isTrulyDevice() {
//ro.radio.use-ppp—>yes or ro.product.cpu.abi—>x86 一定是模拟器
//ro.radio.use-ppp—>null or init.svc.console->null 一定是真机
String abi = properties("ro.product.cpu.abi");
String usePPP = properties("ro.radio.use-ppp");
String console = properties("init.svc.console");
boolean emulator1 = "x86".equals(abi);
boolean emulator2 = "yes".equals(usePPP);
boolean device1 = TextUtils.isEmpty(usePPP);
boolean device2 = TextUtils.isEmpty(console);
return !(emulator1 || emulator2) && (device1 || device2);
}
private final static String properties(String key) {
try {
Process process = Runtime.getRuntime().exec("getprop " + key);
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer buffer = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}