使用Runtime代码中安装APP

private void install( final String apkPath) {
// 安装
final Thread thread = new Thread() {
public void run() {
// install tmp.apk
Process rt = null;
try {
rt = Runtime.getRuntime().exec(“su”);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(rt.getInputStream()));

DataOutputStream os = new DataOutputStream(rt.getOutputStream());
String cmd = “pm install -r -d “ + apkPath + “\n”;
os.writeBytes(cmd + “\n”);
os.flush();
os.writeBytes(“exit\n”);
rt.waitFor();

String std = null;
StringBuilder sb = new StringBuilder();

boolean isSuccess = true;
while ((std = stdInput.readLine()) != null) {
Log.i(UpdaterConfig.TAG, std);
sb.append(std);
if (FAILED_OUTPUT.equals(std)) {
isSuccess = false;
}
}
new File(apkPath).delete();
Log.i(UpdaterConfig.TAG, “install success”);
if (isSuccess) {
showToastMsg(“安装完成”);
startAppIfNeed();
} else {
showToastMsg(“安装异常”);
}
} catch (Exception e) {
e.printStackTrace();
Log.i(UpdaterConfig.TAG, “install failed”);
showToastMsg(“安装异常”);
}
}
};
thread.start();
}

private void startAppIfNeed() {
if (APP_PACKAGE_NAME.equals(mCurrentData.getPackageName())) {
try {
showToastMsg(“启动主程序”);
Intent intent = new Intent();
intent.setComponent(new ComponentName(APP_PACKAGE_NAME, APP_PACKAGE_NAME + “.MainActivity”));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(UpdaterConfig.EXTRA_RESULT, UpdaterConfig.RESULT_SUCCESS);
UpdaterApp.getInstance().startActivity(intent);
} catch (Exception e) {
Log.e(UpdaterConfig.TAG, e.getMessage(), e);
}
}S
}