PackageInstaller作为安装应用的应用,在Android中的地位有些特殊。
看看在AndroidManifest.xml中的声明:
android:configChanges="orientation|keyboardHidden|screenSize"
android:excludeFromRecents="true">
可以看到对application/vnd.android.package-archive这个mime的处理,还有android.intent.action.INSTALL_PACKAGE这个action的处理。
在文件管理器中点击apk文件,或者发送以上intent-filter中对应的action,就会调用PackageInstaller。
我们可以在initiateInstall()这个函数中,通过包名对将要安装的应用进行管控,参考代码如下:
private void initiateInstall() {
String pkgName = mPkgInfo.packageName;
Log.v("AZ","[initiateInstall]pkgName:" + pkgName);
if(pkgName.startsWith("com.zms")){
// Check if there is already a package on the device with this name
// but it has been renamed to something else.
String[] oldName = mPm.canonicalToCurrentPackageNames(new String[] { pkgName });
if (oldName != null && oldName.length > 0 && oldName[0] != null) {
pkgName = oldName[0];
mPkgInfo.packageName = pkgName;
mPkgInfo.applicationInfo.packageName = pkgName;
}
// Check if package is already installed. display confirmation dialog if replacing pkg
try {
// This is a little convoluted because we want to get all uninstalled
// apps, but this may include apps with just data, and if it is just
// data we still want to count it as "installed".
mAppInfo = mPm.getApplicationInfo(pkgName,
PackageManager.GET_UNINSTALLED_PACKAGES);
if ((mAppInfo.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
mAppInfo = null;
}
} catch (NameNotFoundException e) {
mAppInfo = null;
}
mInstallFlowAnalytics.setReplace(mAppInfo != null);
mInstallFlowAnalytics.setSystemApp(
(mAppInfo != null) && ((mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0));
startInstallConfirm();
}else{
finish();
}
} 以上代码的效果就是,只安装包名以“com.zms”开头的应用。其他的不会出现安装界面,直接finish()。