1、基本要求
实现静默安装设备一定是要可以获得Root权限的设备。 cmd界面当shell为#时,代表可以拥有root权限。
2、静默安装
静默安装具体实现方法
public void installs(File apkFile) {
String cmd = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
cmd = "pm install -r -d " + apkFile.getAbsolutePath();
} else {
cmd = "pm install -r -d -i packageName --user 0 " + apkFile.getAbsolutePath();
}
Runtime runtime = Runtime.getRuntime();
try {
Process process = runtime.exec(cmd);
InputStream errorInput = process.getErrorStream();
InputStream inputStream = process.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String error = "";
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader = new BufferedReader(new InputStreamReader(errorInput));
while ((line = bufferedReader.readLine()) != null) {
error += line;
}
if (result.equals("Success")) {
Log.i("installs", "install: Success");
} else {
Log.i("installs", "install: error" + error);
}
} catch (IOException e) {
e.printStackTrace();
}
}
同还要加上安装删除权限
<uses-permission android:name="android.permission.DELETE_PACKAGES" />
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
添加完会发现,这两条权限有提示
警告.png
说这个app不是系统app。这时候就把app打包,通过adb push命令发送到/system/priv-app/<app名>,然后adb reboot重启设备。
3、安装完成自启动
自启动就是直接使用静态广播接收器完成。
public class ReplaceAddRemoveBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_PACKAGE_REPLACED.equals(intent.getAction())) {
Uri data = intent.getData();
if (data != null && context.getPackageName().equals(data.getEncodedSchemeSpecificPart())) {
Log.d("TAG", "更新安装成功.....");
Toast.makeText(context, "更新安装成功", Toast.LENGTH_LONG).show();
// 重新启动APP
Intent intentToStart = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
context.startActivity(intentToStart);
}
}
}
}
在清单文件注册接收器
<receiver
android:name=".ReplaceAddRemoveBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.PACKAGE_REPLACED" />
<data android:scheme="package" />
</intent-filter>
</receiver>
自此就基本完成所有功能。
网友评论