Versions - How can I know the version of my application through code? [duplicate]

2

How can I get this data from the gradle: versionName "1.0.2" Thanks in advance for the help

    
asked by Alex Rivas 16.05.2018 в 14:55
source

2 answers

1

Also if you are using the Gradle / Android Studio plugin, starting with the version 0.7.0 , the version code and the version name are statically available in BuildConfig . Be sure to import the package from your application, and not another BuildConfig :

import com.yourpackage.BuildConfig;
...
int versionCode = BuildConfig.VERSION_CODE;
String versionName = BuildConfig.VERSION_NAME;

You do not need a context object!

Also be sure to specify them in your build.gradle file instead of AndroidManifest.xml .

defaultConfig {
    versionCode 1
    versionName "1.0.2"
}
  

Source So: link

In addition to the response provided by @Einer, if you want to also obtain the code of the version of the application (major, minor and patch) at run time.

You can see the principles of semantic version control .

Get versionName :

packageManager.getPackageInfo(packageName(), PackageManager.GET_META_DATA)
    .versionName; // throws NameNotFoundException

Parse the versionName :

// check versionName against ^\d+\.\d+\.\d+$
final String[] versionNames = versionName.split("\.");
final Integer mayor = Integer.valueOf(versionNames[0]);
final Integer menor = Integer.valueOf(versionNames[1]);
final Integer patch = Integer.valueOf(versionNames[2]);

BE SURE to handle all possible errors.

    
answered by 16.05.2018 / 16:08
source
7

Using the PackgeManager of the context you can get the version of your application:

public String obtenerVersionApp() 
{
    try {
        PackageInfo paquete = this.getPackageManager().getPackageInfo(getPackageName(), 0);
        String versionDeAplicacion = paquete.versionName;

      return versionDeAplicacion;

    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

  return null;
}
    
answered by 16.05.2018 в 14:58