The Android implementation collates PackageManager to get all installer information

  • 2021-01-03 21:02:19
  • OfStack

This article illustrates the Android implementation's approach to collating PackageManager to obtain all installer information. To share for your reference, the details are as follows:


List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);// Gets the package name of the installer 
for (int i = 0; i < packs.size(); i++) {
 PackageInfo p = packs.get(i);// Some package information 
 // Print: version good, version name, package name ....
 Log.i("", "-------" + p.versionCode + "-------" + p.versionName + "--------" 
  + p.packageName + "-------" + p.applicationInfo);
}

The versionCode, versionName value comes from the AndroidManifest.xml file


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.testapk"
   android:versionCode="2" // p.versionCode 
   android:versionName="Version1" // p.versionName
>

Gets versionCode, versionName for the current application in the code


int versionCode = 0;
try {
  versionCode = getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode;
} catch (NameNotFoundException e) {
  e.printStackTrace();
}

Code:


//  By detecting the package name, determine APK Whether to install 
private boolean checkPackageExist(boolean getSysPackages) {
 boolean packageExist = false;
 int versionCode = 0;
 try {
  versionCode = getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode;
 } catch (NameNotFoundException e) {
  e.printStackTrace();
 }
 Log.i("", "-------" + this.getPackageName() + "-------" + versionCode);// Gets the current package name 
 List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
 for (int i = 0; i < packs.size(); i++) {
  PackageInfo p = packs.get(i);
  Log.i("", "-------" + p.versionCode + "-------" + p.versionName + "--------" 
   + p.packageName + "-------" + p.applicationInfo);
  if ((!getSysPackages) && (p.versionName == null)) {
  continue;
  }
  if (p.packageName.equalsIgnoreCase(PACKAGENAME)) {
  packageExist = true;
  break;
  }
 }
 return packageExist;
 }
 // The installation APK
 private void installApk() {
 if (checkFileExist(fileRoot + fileName)) {
  Intent intent = new Intent();
  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  intent.setAction(android.content.Intent.ACTION_VIEW);
  String type = "application/vnd.android.package-archive";
  intent.setDataAndType(Uri.parse("file://" + fileRoot + fileName),
   type);
  startActivity(intent);
 } else {
  downloadapk();
 }
}

Through the above code, plus 1 some network download code, you can do a simplified application market.

I hope this article has been helpful in Android programming.


Related articles: