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 20:10

If you want to use it on xml then add below line on your gradle file:

applicationVariants.all { variant ->
    variant.resValue "string", "versionName", variant.versionName
}

And then use it on your xml like this:

<TextView
        android:gravity="center_horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/versionName" />
查看更多
看风景的人
3楼-- · 2018-12-31 20:11

Use:

try {
    PackageInfo pInfo = context.getPackageManager().getPackageInfo(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;
查看更多
何处买醉
4楼-- · 2018-12-31 20:12

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"
}
查看更多
荒废的爱情
5楼-- · 2018-12-31 20:12
 package com.sqisland.android.versionview;

import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView textViewversionName = (TextView) findViewById(R.id.text);

    try {
        PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        textViewversionName.setText(packageInfo.versionName);

    }
    catch (PackageManager.NameNotFoundException e) {

    }

  }
}
查看更多
登录 后发表回答