Android How to - Get APK version and name








Question

We would like to know how to get APK version and name.

Answer

/*from   w  ww .j  a v a2  s .  c  o  m*/
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;

public class Main {

  public static int getVersionCode(Context context) {
    try {
      PackageInfo packageInfo = context.getPackageManager().getPackageInfo(
          context.getPackageName(), 0);
      int localVersionCode = packageInfo.versionCode;
      return localVersionCode;
    } catch (NameNotFoundException e) {
      e.printStackTrace();
    }
    return -1;
  }

  public static String getVersionName(Context context) {
    try {
      PackageInfo packageInfo = context.getPackageManager().getPackageInfo(
          context.getPackageName(), 0);
      String localVersionName = packageInfo.versionName;
      return localVersionName;
    } catch (NameNotFoundException e) {
      e.printStackTrace();
    }
    return null;
  }
}