Get Android application version?

8

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

<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 whether it would be possible to automatically obtain the current value of the version within an xml resource , so that the value is updated only when the version is changed.

    
asked by A. Cedano 25.10.2017 в 14:45
source

2 answers

4

Within 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 file AndroidManifest.xml

<?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 setting of build.gradle always overwrites the one in the file AndroidManifest.xml

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

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)"
        ...
    }
    
answered by 25.10.2017 / 21:10
source
1

I think it's not possible to do that, what you can do is get the versionName from the gradle using code, and then concatenate in code but not XML

To obtain the versionName you use the following code:

    try {
        PackageInfo pInfo = this.getPackageManager().getPackageInfo(getPackageName(), 0);
        String version = pInfo.versionName;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    
answered by 25.10.2017 в 17:51