【www.bbyears.com--php安装】
android手机在获得root权限之后,可以调用命令的方式静默安装软件,这一点体验是很不错,但是目前网络上关于android静默安装app的代码均出自一人之手,其中有一个非常sb的bug,借用代码的人居然都没有发现,导致网络上几乎所有关于android app静默安装的代码都是错误的。
代码如下new Thread() {
public void run() {
Process process = null;
OutputStream out = null;
InputStream in = null;
try {
// 请求root
process = Runtime.getRuntime().exec("su");
out = process.getOutputStream();
// 调用安装
out.write(("pm install -r " + currentTempFilePath + "
").getBytes());
in = process.getInputStream();
int len = 0;
byte[] bs = new byte[256];
while (-1 != (len = in.read(bs))) {
String state = new String(bs, 0, len);
if (state.equals("Success
")) {
//安装成功后的操作
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.flush();
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start();
这个代码实际上也可以运行起来,在root的手机中,也可以静默安装成功,但是代码有问题就是bug,不知道哪一天这个有问题的代码就会出现错误
下面是修改之后的代码,修改了上面的bug
代码如下new Thread() {
public void run() {
Process process = null;
OutputStream out = null;
InputStream in = null;
try {
// 请求root
process = Runtime.getRuntime().exec("su");
out = process.getOutputStream();
// 调用安装
System.out.println(apkFile.getAbsolutePath());
out.write(("pm install -r " + apkFile.getAbsolutePath() + "
").getBytes());
in = process.getInputStream();
int len = 0;
int readLen = 0;
byte[] bs = new byte[256];
//读出所有的输出数据
while (-1 != (readLen = in.read(bs))) {
len = len + readLen;
//如果读的数据大于缓存区。则停止
if (len > bs.length) {
len -= readLen;
break;
}
}
String state = new String(bs, 0, len);
if (state.startsWith("Success")) {
// 安装成功后的操作
}
else {
//静默安装失败,使用手动安装
installByUser();
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.flush();
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start();
修改的地方就在于从输出流中读取输出数据,可以看出如果输出的数据大于缓存区大小(256),就会导致安装后的操作多次执行,上面这段错误的代码之所以可以运行,是在于输出流的输出为Success ,小于256,但是如果运行指令出错,返回一大推的错误,那么上面的那一段将读取所有的数据,读逐一进行比较。