41

Is there a way for my app to know the android:versionCode from AndroidManifest.xml or do I have to create a separate constant in one of my classes?

700 Software
  • 85,281
  • 83
  • 234
  • 341

3 Answers3

93

I put this in my subclassed android.app.Application but you can use it anywhere you have a context. Just change getPackageManager() to context.getPackageManager().

public int getVersion() {
    int v = 0;
    try {
        v = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
    } catch (NameNotFoundException e) {
        // Huh? Really?
    }
    return v;
}
Fedor
  • 43,261
  • 10
  • 79
  • 89
Jere.Jones
  • 9,915
  • 5
  • 35
  • 38
1

You can get version code simply from <package_name>.BuildConfig#VERSION_CODE reference. It is generated by ADT plugin/Intellij.

Mahendran
  • 2,719
  • 5
  • 28
  • 50
1

Yes, you can access this information via PackageManager.getPackageInfo

Also, see details about versioning in the documentation

uthark
  • 5,333
  • 2
  • 43
  • 59