静默安装(需要root权限) :
/**
* 执行具体的静默安装逻辑,需要手机ROOT。
*
* @param apkPath 要安装的apk文件的路径
* @return 安装成功返回true,安装失败返回false。
*/
private boolean silentInstall(String apkPath) {
boolean result = false;
DataOutputStream dataOutputStream = null;
BufferedReader errorStream = null;
BufferedReader successStream = null;
Process process = null;
try {
// 申请 su 权限
process = Runtime.getRuntime().exec("su");
dataOutputStream = new DataOutputStream(process.getOutputStream());
// 执行 pm install 命令
String command = "pm install -r " + apkPath + "\n";
dataOutputStream.write(command.getBytes(Charset.forName("UTF-8")));
dataOutputStream.writeBytes("exit\n");
dataOutputStream.flush();
process.waitFor();
errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
StringBuilder errorMsg = new StringBuilder();
String line;
while ((line = errorStream.readLine()) != null) {
errorMsg.append(line);
}
StringBuilder successMsg = new StringBuilder();
successStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
// 读取命令执行结果
while ((line = successStream.readLine()) != null) {
successMsg.append(line);
}
// 如果执行结果中包含 Failure 字样就认为是操作失败,否则就认为安装成功
if (!(errorMsg.toString().contains("Failure") || successMsg.toString().contains("Failure"))) {
result = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (process != null) {
process.destroy();
}
if (dataOutputStream != null) {
dataOutputStream.close();
}
if (errorStream != null) {
errorStream.close();
}
if (successStream != null) {
successStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
被更新的apk中!:Mainfest中注册广播 :
<receiver android:name=".receiver.MainReceiver">
<intent-filter>
<action android:name="android.intent.action.PACKAGE_REPLACED" />
<data android:scheme="package" />
</intent-filter>
</receiver>
<data android:scheme="package" />这一句很关键!
onReceive方法:
if (intent.getAction().equals(android.intent.action.PACKAGE_REPLACED)) {
String packageName = intent.getData().getEncodedSchemeSpecificPart();
if (packageName.equals(PACKAGE_NAME)) {
LogUtils.e(TAG,"正在重新启动Activity...");
// 重新启动APP
Intent intentToStart = context.getPackageManager().getLaunchIntentForPackage(packageName);
context.startActivity(intentToStart);
}
}