关键点:
1.手机已经root
2.执行静默安装的程序需要申请root权限,代码如下:
/**
* 应用程序运行命令获取 Root权限,设备必须已破解(获得ROOT权限)
*
* @return 应用程序是/否获取Root权限
*/
public static boolean upgradeRootPermission(String pkgCodePath) {
Process process = null;
DataOutputStream os = null;
try {
String cmd="chmod 777 " + pkgCodePath;
process = Runtime.getRuntime().exec("su"); //切换到root帐号
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(cmd + "\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (Exception e) {
return false;
} finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
}
}
return true;
}
3.执行静默安装的程序必须用android framework签名文件来签名
签名下载地址:http://download.youkuaiyun.com/detail/lhangtk/8274143
4.执行安装的代码使用pm install命令,相关的java代码如下:
/**
* 安装应用
* @param apkAbsolutePath 安装应用的路径
* @return 安装结果的控制台输出
*/
public String install(String apkAbsolutePath) {
//初始化pm指令
String[] args = {"pm", "install", "-r", apkAbsolutePath};
String result = "";
//进程生成器,将指令封装成独立的进程,进行调用
ProcessBuilder processBuilder = new ProcessBuilder(args);
//进程
Process process = null;
InputStream errIs = null;
InputStream inIs = null;
try {
//字节流,临时存储控制台的输出内容
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int read = -1;
//执行安装apk的pm指令
process = processBuilder.start();
//接收控制台输出的异常情况,输入流
errIs = process.getErrorStream();
while ((read = errIs.read()) != -1) {
baos.write(read);
}
baos.write("\r\n".getBytes());
//正常输出
inIs = process.getInputStream();
while ((read = inIs.read()) != -1) {
baos.write(read);
}
byte[] data = baos.toByteArray();
//将控制台输出转化为字符串返回
result = new String(data);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {//最后必须将所有输入输出流关闭
try {
if (errIs != null) {
errIs.close();
}
if (inIs != null) {
inIs.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (process != null) {
process.destroy();
}
}
return result;
}
文章参考http://blog.youkuaiyun.com/lhangtk/article/details/42006087
演示地址为http://download.youkuaiyun.com/detail/shuaicike/9748884,需要先放一个名称为app-debug.apk的安装包在SD卡根目录,亲测在三星note2手机可跑~~