1: 由Package Name获取其package的环境变量
根据此变量可以获取相应package的resource
Context authContext = createPackageContext(desc.packageName, 0);
icon = authContext.getResources().getDrawable(desc.iconId);
label = authContext.getResources().getText(desc.labelId);
2: 根据APK URI 获取APP 信息
/*
* Utility method to get application information for a given packageURI
*/
public static ApplicationInfo getApplicationInfo(Uri packageURI) {
final String archiveFilePath = packageURI.getPath();
PackageParser packageParser = new PackageParser(archiveFilePath);
File sourceFile = new File(archiveFilePath);
DisplayMetrics metrics = new DisplayMetrics();
metrics.setToDefaults();
PackageParser.Package pkg = packageParser.parsePackage(sourceFile, archiveFilePath, metrics, 0);
if (pkg == null) {
return null;
}
return pkg.applicationInfo;
apk时候已经安装
public static boolean isPackageAlreadyInstalled(Activity context, String pkgName) {
List<PackageInfo> installedList = context.getPackageManager().getInstalledPackages(
PackageManager.GET_UNINSTALLED_PACKAGES);
int installedListSize = installedList.size();
for(int i = 0; i < installedListSize; i++) {
PackageInfo tmp = installedList.get(i);
if(pkgName.equalsIgnoreCase(tmp.packageName)) {
return true;
}
}
return false;
}
获取app icon 和 name
public static View initSnippetForInstalledApp(Activity pContext,
ApplicationInfo appInfo, int snippetId) {
View appSnippet = pContext.findViewById(snippetId);
String pkgName = appInfo.packageName;
PackageManager pm = pContext.getPackageManager();
CharSequence label = appInfo.loadLabel(pm);
Drawable icon = appInfo.loadIcon(pm);
((ImageView)appSnippet.findViewById(R.id.app_icon)).setImageDrawable(icon);
((TextView)appSnippet.findViewById(R.id.app_name)).setText(label);
return appSnippet;
}
安装APP 代码
PackageManager pm = getPackageManager();
installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
String installerPackageName = getIntent().getStringExtra(
Intent.EXTRA_INSTALLER_PACKAGE_NAME);
PackageInstallObserver observer = new PackageInstallObserver();
pm.installPackage(mPackageURI, observer, installFlags, installerPackageName);
class PackageInstallObserver extends IPackageInstallObserver.Stub {
public void packageInstalled(String packageName, int returnCode) {
}
}
卸载App
PackageDeleteObserver observer = new PackageDeleteObserver();
getPackageManager().deletePackage(mAppInfo.packageName, observer, 0);
class PackageDeleteObserver extends IPackageDeleteObserver.Stub {
public void packageDeleted(boolean succeeded) {
Message msg = mHandler.obtainMessage(UNINSTALL_COMPLETE);
msg.arg1 = succeeded?SUCCEEDED:FAILED;
mHandler.sendMessage(msg);
}
}