Get application version programmatically in android [duplicate]

Solution 1:

If you're using the Gradle plugin/Android Studio, as of version 0.7.0, version code and version name are available statically in BuildConfig. Make sure you import your app's package, and not another BuildConfig:

import com.yourpackage.BuildConfig;
...
int versionCode = BuildConfig.VERSION_CODE;
String versionName = BuildConfig.VERSION_NAME;

No Context object needed!

Also make sure to specify them in your build.gradle file instead of the AndroidManifest.xml.

defaultConfig {
    versionCode 1
    versionName "1.0"
}

Solution 2:

Use:

try {
    PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
    String version = pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}

And you can get the version code by using this

int verCode = pInfo.versionCode;

Solution 3:

Slightly shorter version if you just want the version name.

try{
    String versionName = context.getPackageManager()
    .getPackageInfo(context.getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return false;
}