Get Android app version?

Question:

I have the name of my application in strings.xml of the res/values folder:

<string name="app_name">Liturgia+</string>

I would like to change that value, adding the current version of the app. Assuming the current version is 1.3 , I would like something like this:

Liturgia+ (v. 1.3)

My question is if it would be possible to automatically get the current value of the version inside an xml resource , so that the value is updated only when the version changes.

Answer:

Inside your build.gradle you can define the versionName , which is a String that indicates the version:

android {
        ...
        versionCode 1
        versionName "(v. 1.3)"
        ...
    }

These values ​​can also be defined within your AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jorgesys.ussd"
    android:versionCode="1"
    android:versionName="(v. 1.3)">

just remember that the build.gradle setting always overrides the AndroidManifest.xml file

Given the above, you can get the value of versionName like this :

public String getVersionName(Context ctx){
    try {
    return ctx.getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return "";
    }
}

another way is simply (requires the project to be built):

public String getVersionName(){
     return BuildConfig.VERSION_NAME;
 }

The String value of versionName can be concatenated to the name of your application.


You can even define as versionName the value Liturgia+ (v. 1.3) , example:

android {
        ...
        versionCode 1
        versionName "Liturgia+ (v. 1.3)"
        ...
    }
Scroll to Top