Android Tutorial: How to get the app version number

How to get the app version number

In this tutorial I will show you how you can retrieve the app’s version number in runtime. This can be useful if you want to inform the users which version of the app they are running or if you want to create a function that uses the app version as a parameter, (for example a help function that retrieves it’s information online) you can also use the version number to check if an user has updated your app from a previous version.

For this tutorial I will use a button that will trigger code that updates a label to display the current version number of the app.

First we will begin by putting a button and a textview on a layout called “activity_main.xml”

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical" tools:context=".MainActivity">
    <Button
        android:id="@+id/btn_get_version_info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_get_version_number" />
    <TextView
        android:id="@+id/textview_version_info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

As you can see I have created a button called “btn_get_version_info”, its text is specified by a resource string, we will set its on click event later in the onCreate method of our main activity.
The text for the button is set in the strings resource file, this is located in the file “res/values/strings.xml”.

<resources>
    <string name="app_name">App version info example</string>

    <string name="button_get_version_number">Get version number</string>
</resources>

Now we need to create our activity. I Have named my activity MainActivity and the corresponding class file is named “MainActivity.java”. As you can see in the next part of the code I am using the support library in this example. This of course is not necessary, you can also extend from the Activity class if you want to.

package example.com.appversioninfoexample;

import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

}

Next we add an OnClickListener for the button in the OnCreate method.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn_get_version_info).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                
            }
        });
    }

Now we need to write the code that gets the app’s version information and display it in the label. To get the version information we will use the package manager. This class can give information about installed packages on the device. You can use the package manager to get a list of all installed packages or the information of just one package. Besides information about the version number you can also read information like the app’s activities, services, features, permissions etc. For this example we are only interested in the app’s version information.

I’ve started by creating a private method called getVersionInfo(). As you can see I have surrounded the call to the package manager and package info class with a try except to catch any NameNotFoundException. Although this should not happen it is best practice to do so since the getPackageInfo call can throw this error when the package we are requesting the information for can not be found.
getPackageInfo gives us back an object of the class PackageInfo. This object contains our actual version information. This function requires two parameters, the first parameter is the package name and the second parameter is used for flags specifying if we want additional information about the package like activities, permissions, services etc. In our case we are only interested in the version information so we use 0 for the flags parameter.

Once we have got the version information from the package manager we can use this to update our label on the activity. First we get the label by its id, next we set the text of the label with the setText() function. I’ve used the String.format function to format the text and used the versionName and versionCode as the two parameters to be replaced in the string.

    //get the current version number and name
    private void getVersionInfo() {
        String versionName = "";
        int versionCode = -1;
        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            versionName = packageInfo.versionName;
            versionCode = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        TextView textViewVersionInfo = (TextView) findViewById(R.id.textview_version_info);
        textViewVersionInfo.setText(String.format("Version name = %s \nVersion code = %d", versionName, versionCode));
    }

Last thing is to call the new getVersionInfo() method from the button’s OnClickListener, and that’s it.

        findViewById(R.id.btn_get_version_info).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getVersionInfo();
            }
        });


Check the version code

In the next part I want to give you an example on how you can use the version code to check if an user is running your app for the first time or has updated your app from a previous version.

I Have started by creating a private method that we can call to perform the check. This method will read a value called “app_version” from the shared preferences. I will store the current version of the app that the user is running later.
If this is the first time the user runs the app the value will not exist in the shared preferences, in that case the getInt method will return the default value which I have set to 0.

Once we got the known previous version we can compare it to the current version of the app. To get the current version of the app I have created an other method called getCurrentAppVersionCode(). We know that the user is running this current version for the first time if the previous version and the current version do not match. In that case we only need to check if the previous version is higher than 0, (the default value) if so then the user has updated the app, if not then the user is running the app for the first time.

Once we are done with the check the method stores the current version in the shared preferences so the next time the method is run it can get the stored value again from the shared preferences.

    private void checkAppVersion() {
        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        int currentAppVersionCode = getCurrentAppVersionCode();
        int oldAppVersion = prefs.getInt("app_version", 0);
        if (oldAppVersion < currentAppVersionCode) {
            try {
                if (oldAppVersion > 0)
                    Toast.makeText(this, String.format("App updated from version %d", oldAppVersion), Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(this, String.format("App started for the first time", oldAppVersion), Toast.LENGTH_SHORT).show();
            } finally {
                SharedPreferences.Editor preferencesEditor = prefs.edit();
                preferencesEditor.putInt("app_version", currentAppVersionCode);
                preferencesEditor.commit();
            }
        }
    }

    private int getCurrentAppVersionCode() {
        int versionCode = -1;
        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            versionCode = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

Add a call to the checkAppVersion() method in the onCreate to perform the app version check.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn_get_version_info).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getVersionInfo();
            }
        });

        checkAppVersion();
    }

Version info in the Gradle build file

        versionName = BuildConfig.VERSION_NAME;
        versionCode = BuildConfig.VERSION_CODE;
        textViewVersionInfo.setText(textViewVersionInfo.getText() +
                String.format("\nGradle build config version name = %s \nGradle build config version code = %d", versionName, versionCode));

There is an other way to get the version information of your app, this method requires that you are using Gradle to build your app. When building your app with Gradle Gradle will automatically create a BuildConfig class with the information from your Gradle build file. The benefit of using this class is that you can use if from anywhere in your project’s code and it does not require a context object like you would need to get an instance of the package manager. You do need to set the version name and version code in your build.gradle file as shown below.

Content of the “build.gradle” file for this example project.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "example.com.appversioninfoexample"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.1'
}

I hope this post will help you develop your Android app.
Till next post.

Example project

An example project for this article can be found on Github.
https://github.com/MartinvanZ/AppVersionInfoExample

More information

For more information see the developer online reference:
http://developer.android.com/reference/android/content/pm/PackageManager.html
http://developer.android.com/reference/android/content/pm/PackageInfo.html

Leave a Reply

Your email address will not be published. Required fields are marked *