Detect my app's own android:versionCode at run

2019-03-22 12:07发布

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?

3条回答
Rolldiameter
2楼-- · 2019-03-22 12:42

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

查看更多
别忘想泡老子
3楼-- · 2019-03-22 12:44

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;
}
查看更多
再贱就再见
4楼-- · 2019-03-22 12:49

Yes, you can access this information via PackageManager.getPackageInfo

Also, see details about versioning in the documentation

查看更多
登录 后发表回答