How to get the build/version number of your Androi

2018-12-31 19:45发布

I need to figure out how to get or make a build number for my Android application. I need the build number to display in the UI.

Do I have to do something with AndroidManifest.xml?

28条回答
旧人旧事旧时光
2楼-- · 2018-12-31 19:58

Always do it with try catch block:

String versionName = "Version not found";

try {
    versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
    Log.i(TAG, "Version Name: " + versionName);
} catch (NameNotFoundException e) {
    // TODO Auto-generated catch block
    Log.e(TAG, "Exception Version Name: " + e.getLocalizedMessage());
}
查看更多
大哥的爱人
3楼-- · 2018-12-31 19:59

Slightly shorter version if you just want the version name.

String versionName = context.getPackageManager()
    .getPackageInfo(context.getPackageName(), 0).versionName;
查看更多
裙下三千臣
4楼-- · 2018-12-31 19:59
private String GetAppVersion(){
        try {
            PackageInfo _info = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
            return _info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "";
        }
    }

    private int GetVersionCode(){
        try {
            PackageInfo _info = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
            return _info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return -1;
        }
    }
查看更多
无色无味的生活
5楼-- · 2018-12-31 20:01

Use BuildConfig class

String versionName = BuildConfig.VERSION_NAME;
int versionCode = BuildConfig.VERSION_CODE;

build.gradle(app)

 defaultConfig {
    applicationId "com.myapp"
    minSdkVersion 19
    targetSdkVersion 27
    versionCode 17
    versionName "1.0"
   }
查看更多
泪湿衣
6楼-- · 2018-12-31 20:02
  PackageInfo pinfo = null;
    try {
        pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    int versionNumber = pinfo.versionCode;
    String versionName = pinfo.versionName;
查看更多
笑指拈花
7楼-- · 2018-12-31 20:03

There are two parts you need: android:versionCode android:versionName

versionCode is a number, and every version of the app you submit to the Market needs to have a higher number then the last.

VersionName is a string, and can be anything you want it to be. This is where you define your app as "1.0" or "2.5" or "2 Alpha EXTREME!" or whatever.

Example:

To access it in code, do something like:

PackageManager manager = this.getPackageManager();
PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
Toast.makeText(this,
     "PackageName = " + info.packageName + "\nVersionCode = "
       + info.versionCode + "\nVersionName = "
       + info.versionName + "\nPermissions = " + info.permissions, Toast.LENGTH_SHORT).show();
查看更多
登录 后发表回答