前言
- 客户有个需求是整个系统不能安装任何APk,包括使用PackageInstaller安装以及使用install命令安装都不行,只能安装白名单里面的apk或者是打开能安装的开关之后才能进行安装
环境
实现
首先拦截 shell下的 install 命令
- 找到frameworks/base/cmds/pm/src/com/android/commands/pm/Pm.java文件,在runInstall方法添加如下代码拦截 install 命令
private int runInstall() throws RemoteException {
+//通过系统属性拦截命令安装Apk,属性名可以随意指定,此处只是一个示例
+ if(!SystemProperties.getBoolean("persist.sys.allow.installapk", false)){
+ Log.d("zhuw","Pm --- APK installation blocking");
+ System.out.println("Pm --- APK installation blocking");
+ return 1;
+ }
....
省略代码
....
}
拦截packageinstaller安装APk
- 找到packages/apps/PackageInstaller/src/com/android/packageinstaller/PackageInstallerActivity.java文件 在startInstall方法添加代码
private void startInstall() {
+ if(!SystemProperties.getBoolean("persist.sys.allow.installapk", false)){
+ // 检查一下是不是白名单的apk
+ //获取可以安装的apk包名数组
+ String[] homeApkNames = getHomeApkNames();
+ boolean isHomeApk = false;
+ for(String:homeApkNames){
+ Log.d("zhuw"," mPkgInfo.packageName -> " + +mPkgInfo.packageName + " s = "+ s);
+ if(s.equals(mPkgInfo.packageName)){
+ isHomeApk = true;
+ break;
+ }
+ }
+ if(!isHomeApk) {
+ Log.d("zhuw","PackageInstaller --- APK installation blocking");
+ new AlertDialog.Builder(this)
+ .setMessage("管理员禁止安装应用,如有需要,请联系管理员安装")
+ .setPositiveButton(R.string.cancel,
+ ((dialog, which) -> finish()))
+ .show();
+ return;
+ }
+ }
if(localLOGV) Log.i(TAG, "downloaded app uri="+mPackageURI);
startActivity(newIntent);
finish();
}