Android How to - Get Current Version Name From PackageManager








Question

We would like to know how to get Current Version Name From PackageManager.

Answer

/*from w  w  w . j a  v a2s . c o m*/
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

public class Main {
  
  public static String getCurrentVersionName(Context context) {
    String currentVersionName = "";
    
    try {
      PackageManager pm  = context.getPackageManager();
      PackageInfo pi    = pm.getPackageInfo(context.getPackageName(), 0);
      currentVersionName  = pi.versionName;
      if (currentVersionName == null || currentVersionName.length() <= 0) {
        currentVersionName  = "1.0.0";
      }
    } catch (Exception e) {
      currentVersionName  = "1.0.0";
    }
    
    return currentVersionName;
  }
}