判断App是否在模拟器上运行

我们之前看友盟的统计,发现有一些bug,都是在模拟器类型报的错,我们干脆就不让在模拟器安装了,下面我们来看一下。

首先我们来看一下Runtime这个类,他是一个与JVM运行时环境有关的类,这个类是Singleton的。

1
Allows Java applications to interface with the environment in which they are running. Applications can not create an instance of this class, but they can get a singleton instance by invoking getRuntime().

上面是在developer上面摘的Runtime.

这里面有这么几个重要方法,exec(),gc(),getRuntime(),maxMemory(),exit()等等,我们今天主要看exec方法,exec有六个重载。也就是我们今天要看的。

如果想与调用的程序进行交互,那么就要使用该方法的返回对象Process了,通过Process的getInputStream(),getOutputStream()和getErrorStream()方法可以得到输入输出流,然后通过InputStream可以得到程序对控制台的输出信息,通过OutputStream可以给程序输入指令,这样就达到了程序的交换功能。

先来上代码,光说理论就没意思了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* 判断是否在模拟器上运行
*
* @return
*/
public static boolean isRunningInEmualtor() {
boolean quemuKernel = false;
Process process = null;
DataOutputStream os = null;
BufferedReader in = null;
try {
process = Runtime.getRuntime().exec(".\\a.exe");
os = new DataOutputStream(process.getOutputStream());
in = new BufferedReader(new InputStreamReader(
process.getInputStream(), "GBK"));
os.writeBytes("exit\n");
os.flush();
process.waitFor();
quemuKernel = (Integer.parseInt(in.readLine()) == 1);
} catch (Exception e) {
quemuKernel = false;
} finally {
if (process != null) {
process.destroy();
process = null;
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
in = null;
}
if (os != null) {
try {
os.close();
os = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
return quemuKernel;
}

第一行的“.\a.exe”是要执行的程序名,Runtime.getRuntime()返回当前应用程序的Runtime对象,该对象的exec()方法指示Java虚拟机创建一个子进程执行指定的可执行程序,并返回与该子进程对应的Process对象实例。通过Process可以控制该子进程的执行或获取该子进程的信息。

上面这个代码直接拿着用就好,然后把执行的程序名换成自己的就好。

1
2
3
4
5
6
if (Utils.isRunningInEmualtor()) {
Toast.makeText(IgniteApplication.getInstance(), "我们不支持在模拟器上运行哦",
Toast.LENGTH_SHORT).show();
finish();
return;
}

版权声明:



除非注明,本博文章均为原创,转载请以链接形式标明本文地址。

坚持原创技术分享,您的支持将鼓励我继续创作!