很简单的一段代码,但是前提必须是手机已经root完毕
public static boolean installFile(File path,Context context){
boolean result = false;
Process process = null;
OutputStream out = null;
InputStream in = null;
String state = null;
try {
// 请求root
process = Runtime.getRuntime().exec("su");
out = process.getOutputStream();
// 调用安装,将文件写入到process里面
out.write(("pm install -r " + path + "\n").getBytes());
//这里拿到输出流,开始安装操作
in = process.getInputStream();
int len = 0;
byte[] bs = new byte[256];
while (-1 != (len = in.read(bs))) {
state = new String(bs, 0, len);
if (state.equals("Success\n")) {
// 安装成功后的操作
result = true;
Log.e("成功", state);
break;
}
}
} 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();
}
}
return result;
}