Android How to - Get APK version Name by package name








Question

We would like to know how to get APK version Name by package name.

Answer

//from   w  ww .  java2s  . com
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;

public class Main {

  public String getApkVersionName(Context context, String pkgName)
      throws NameNotFoundException {
    PackageInfo pkgInfo = context.getApplicationContext().getPackageManager()
        .getPackageInfo(pkgName, 0);
    return pkgInfo.versionName;
  }

  public int getApkVersionCode(Context context, String pkgName)
      throws NameNotFoundException {
    PackageInfo pkgInfo = context.getApplicationContext().getPackageManager()
        .getPackageInfo(pkgName, 0);
    return pkgInfo.versionCode;
  }
}