code: public static String getVersionName(Context context) {
          try {
              PackageManager manager = context.getPackageManager();
              PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
              return info.versionName;
          } catch (NameNotFoundException e) {
              throw new IllegalStateException("no such package installed on the device: ", e);
          }
      }
docs: Read version name from the manifest of the context.
  @param context the context.
  @return the version name.
  @throws java.lang.IllegalStateException if the target package is not installed.