公司产品基于7.0开发,需要实现覆盖升级。之前的产品覆盖升级基于5.1系统,在7.0上不起作用。网上参考了许多博客。最终稀里糊涂的成功了,简单记录。
核心代码只有一句
String command = "pm install -r -i 包名 --user 0 apk路径";
execInstallCommand(new String[]{command})
public static final String COMMAND_EXIT = "exit\n";
public static final String COMMAND_LINE_END = "\n";
public static void execInstallCommand(String[] commands) {
Process process = null;
BufferedReader successResult = null;
BufferedReader errorResult = null;
DataOutputStream os = null;
try {
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
for (String command : commands) {
if (command == null) {
continue;
}
// donnot use os.writeBytes(commmand), avoid chinese charset error
os.write(command.getBytes());
os.writeBytes(COMMAND_LINE_END);
os.flush();
}
os.writeBytes(COMMAND_EXIT);
os.flush();
process.waitFor();
} catch (IOException e) {
Log.e(TAG,e.getMessage());
} catch (Exception e) {
Log.e(TAG,e.getMessage());
} finally {
try {
if (os != null) {
os.close();
}
if (successResult != null) {
successResult.close();
}
if (errorResult != null) {
errorResult.close();
}
} catch (IOException e) {
Log.e(TAG, "execCommand: ", e);
}
if (process != null) {
process.destroy();
}
}
}