How to get the build/version number of your Android application?

前端 未结 30 1768
刺人心
刺人心 2020-11-22 11:00

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

30条回答
  •  无人及你
    2020-11-22 11:23

    Here is a clean solution, based on the solution of scottyab (edited by Xavi). It shows how to get the context first, if it's not provided by your method. Furthermore it uses multiple lines instead of calling multiple methods per line. This makes it easier when you have to debug your application.

    Context context = getApplicationContext(); // or activity.getApplicationContext()
    PackageManager packageManager = context.getPackageManager();
    String packageName = context.getPackageName();
    
    String myVersionName = "not available"; // initialize String
    
    try {
        myVersionName = packageManager.getPackageInfo(packageName, 0).versionName;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    

    Now that you received the version name in the String myVersionName, you can set it to a TextView or whatever you like..

    // set version name to a TextView
    TextView tvVersionName = (TextView) findViewById(R.id.tv_versionName);
    tvVersionName.setText(myVersionName);
    

提交回复
热议问题