实现静默安装首先手机就有root权限或者是system应用(使用厂商提供的签名文件签名过)
下面是实现静默升级的步骤:
1、在AndroidManifest文件中添加权限
<uses-permission
android:name="android.permission.INSTALL_PACKAGES"
tools:ignore="ProtectedPermissions" />
并且在application标签里面加入属性:android:sharedUserId="android.uid.system"
2、在apk文件下载完成后,首先进行修改权限操作
chmod("777",filePath);
public static void chmod(String permission, String path) {
String command = "chmod " + permission + " " + path;
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec(command);
} catch (IOException e) {
e.printStackTrace();
}
}
3、调用静默安装函数
// 静默安装,1-安装成功,或没有升级文件,2-升级安装出现异常,-1-程序异常
public static int installBySlient(Context context, String filePath) {
int result = 0;
try {
File file = new File(filePath);
if (filePath == null || filePath.length() == 0
|| (file = new File(filePath)) == null
|| file.length() <= 0 || !file.exists() || !file.isFile()) {
return 1;
}
String[] args = {"pm", "install", "-r", filePath};
ProcessBuilder processBuilder = new ProcessBuilder(args);
Process process = null;
BufferedReader successResult = null;
BufferedReader errorResult = null;
StringBuilder successMsg = new StringBuilder();
StringBuilder errorMsg = new StringBuilder();
try {
process = processBuilder.start();
successResult = new BufferedReader(new InputStreamReader(
process.getInputStream()));
errorResult = new BufferedReader(new InputStreamReader(
process.getErrorStream()));
String s;
while ((s = successResult.readLine()) != null) {
successMsg.append(s);
}
while ((s = errorResult.readLine()) != null) {
errorMsg.append(s);
}
} catch (IOException e) {
e.printStackTrace();
result = 2;
} catch (Exception e) {
e.printStackTrace();
result = 2;
} finally {
try {
if (successResult != null) {
successResult.close();
}
if (errorResult != null) {
errorResult.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (process != null) {
process.destroy();
}
}
if (successMsg.toString().contains("Success")
|| successMsg.toString().contains("success")) {
result = 1;
} else {
result = 2;
}
} catch (Exception e) {
result = -1;
}
return result;
}
到这里,静默安装就已经完成了,但是这样有点美中不足,apk升级完成后不会自动启动,我们可以监听系统发送的广播,使用静态注册广播的方式,实现apk自启动
1、在需要启动的Activity中添加静态广播接收类
public static class UpdateRestartReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.PACKAGE_REPLACED")) {
Toast.makeText(context, "已升级到新版本", Toast.LENGTH_SHORT).show();
Intent intent2 = new Intent(context, LivePlayerActivity.class);
intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent2);
}
}
}
2、接着,在AndroidManifest中注册广播
<receiver android:name=".iptv.LivePlayerActivity$UpdateRestartReceiver">
<intent-filter>
<action android:name="android.intent.action.PACKAGE_REPLACED" />
<data android:scheme="package" />
</intent-filter>
</receiver>