Android高级开发交流群:484966421 。
微信公众号:oshome2015
在网上各种方法实现静默安装,但是大多数是采用方法是在root权限下,通过执行pm install 的方式去安装apk,但是很多情况下。获取root权限并不是很容易的。本文介绍一种非root情况下的一种静默安装方式,这种方式在智能电视运用的场景很多,很多例如当呗,沙发网等应用市场都是通过这种方式实现的非root权限的静默安装。
基本原理:
在应用程序内创建一个单独进程,执行adb install -r apkname.相当于在你的应用内部执行adb install 操作。这样为什么可以成功,有兴趣的同学可以百度一下adb的原理。后面的我也会详细分析一下adb原理,对此做一个完整的分析。
测试例子:
localRT=Runtime.getRuntime();
try{
localRT.exec("setprop persist.service.adb.enable 1").waitFor();
Process localProcess=localRT.exec("adb install -r "+packagename);
new StreamGobbler(localProcess,localProcess.getErrorStream(),"INFO").start();
result= localProcess.waitFor();
debug.LogE("result= " + result);
if(result==0){
return result;
}else{
debug.LogE(" silent install fail");
Process lp=localRT.exec("chmod -R 777 "+ Application.localFile);
....
}
catch(Exception e){
debug.LogE("install exception ="+e);
注意:在这儿用了StreamGobbler这个类处理localProcess的输出,主要原因是,如果不处理localProcess输出信息,程序会随机卡死这儿,你也无法确定是不是执行完成了。
class StreamGobbler extends Thread
{
InputStream is;
String type;
Process mP;
StreamGobbler(Process p,InputStream is, String type)
{
this.is = is;
this.type = type;
mP=p;
}
public void run()
{
try
{
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null){
debug.LogV( type + " > " + line);
if(line.contains("error")){
mP.destroy();
}
}
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}