1562

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 AndroidManifest.xml?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Fahad Ali Shaikh
  • 15,645
  • 3
  • 15
  • 4
  • 1
    Duplicated: http://stackoverflow.com/questions/4471025/how-can-you-get-the-manifest-version-number-from-the-apps-layout-xml-variable – Idemax Sep 26 '16 at 14:19
  • 36
    To get the version code use `int versionCode = BuildConfig.VERSION_CODE;` and to get the version name `String versionName = BuildConfig.VERSION_NAME;` – Lukas Dec 21 '19 at 11:33

36 Answers36

2287

If you're using the Gradle plugin/Android Studio, as of version 0.7.0, version code and version name are available statically in BuildConfig. Make sure you import your app's package, and not another BuildConfig:

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

No Context object needed!

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

defaultConfig {
    versionCode 1
    versionName "1.0"
}
Sam Dozor
  • 40,335
  • 6
  • 42
  • 42
  • 22
    Beware, for a multi-module project you may get unexpected results when querying for this in a specific module. Probably best to bind this in some global name space in your main Application/Activity class. – inder Jan 14 '15 at 01:04
  • is there any way that i can get the version code of my app which is in playstore? – AndroidManifester Apr 18 '15 at 13:45
  • 11
    This does not work if you want to use it in a library module to get info about the application. There's no BuildConfig file in the library module – dumazy Oct 08 '15 at 14:30
  • 15
    @dumazy. there can be a BuildConfig for a library module but you won't be getting the application's build information. You will be getting the library's information. – John Cummings Dec 01 '15 at 21:46
  • 1
    I suppose the empty string result of this method is due to importing the wrong BuildConfig when writing this code. When I pasted it into my project I had a multitude of options to choose from for all libraries I was using and the modules as well. I just imported the one associated with my own package name – Kaloyan Roussev Dec 07 '15 at 11:06
  • 3
    this is not working with `com.android.tools.build:gradle:1.3.0` – Kushal Feb 18 '16 at 14:02
  • 1
    This doesn't work if your build gradle uses `versionNameOverride` to dynamically set the version. It will show whatever your gradle as `versionCode` has set, but this could be different then the value stored in your release. In case of the `versionName` It could be also different to what the store listing shows. – tobltobs Nov 06 '19 at 17:03
  • If using [gradle version 8.0 or higher](https://stackoverflow.com/a/76576245/8890753), make sure you set `build.config = true` inside of `buildfeatures` – Kenny Sexton Aug 14 '23 at 21:39
2200

Use:

try {
    PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
    String version = pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}

And you can get the version code by using this

int verCode = pInfo.versionCode;
macros013
  • 739
  • 9
  • 10
plus-
  • 45,453
  • 15
  • 60
  • 73
489

Slightly shorter version if you just want the version name.

try{
    String versionName = context.getPackageManager()
    .getPackageInfo(context.getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return false;
}
Naveed Ahmad
  • 6,627
  • 2
  • 58
  • 83
scottyab
  • 23,621
  • 16
  • 94
  • 105
  • 91
    Excellent. This should probably be surrounded with try/catch for NameNotFoundException. – IgorGanapolsky Dec 06 '12 at 14:50
  • 6
    +1 I've implemented your solution which works great! However, this solution should be surrounded by try and catch like Igor said AND it is good practice (e.g. for debugging) to put each method call on a separate line instead of calling context.methodName().subMethod().anotherSubMethod() etc. on a single line. Therefore I provided a cleaner solution [below](http://stackoverflow.com/a/18352981/1694500) – Michael Dec 20 '13 at 10:52
  • 1
    That's the right solution, thanks ;) But, as suggested by @IgorGanapolsky, it needs to be surrounded with try / catch :) – andrea.rinaldi Jun 20 '14 at 08:28
  • 2
    for those using Gradle - there is a simpler solution. See my answer below. – Sam Dozor Jul 01 '14 at 18:50
  • @Igor Ganapolsky: Just use Exception instead of NameNotFoundException to catch all possible exceptions, it makes your code/program more robust. – Codebeat May 23 '15 at 02:45
  • 1
    @Erwinus I wholeheartedly disagree with the notion of using a generic Exception to catch stuff like this. More fine-grained exceptions demonstrate a developer's understanding of possible errors. – IgorGanapolsky May 26 '15 at 14:28
  • 2
    @IgorGanapolsky: That's true but what if the programmer don't understand it? I don't think the user of the application does appreciate any kind of exception. With all kind of Android flavors, there is a change that something unexpected happen and it will be stupid when something simple like this shutdown your app. If that happen, you can assume the programmer don't understand what the user wants because it's very easy to avoid this. Besides, you can log exceptions if you want to know what's going wrong, there is a description. No matter what kind of exception, an unhandled exception is wrong. – Codebeat May 26 '15 at 14:48
  • 1
    What are the cases when exception may be thrown? If the app is running and looking for self version is there a chance that PackageManager will not find it? – nsk Mar 04 '21 at 13:24
  • This is deprecated starting from Lollipop. Please be aware Android does not recommend this solution in production. – Juan Mendez Feb 09 '22 at 16:47
210

There are two parts you need:

  • android:versionCode
  • android:versionName

versionCode is a number, and every version of the app you submit to the market needs to have a higher number than the last.

VersionName is a string and can be anything you want it to be. This is where you define your app as "1.0" or "2.5" or "2 Alpha EXTREME!" or whatever.

Example:

Kotlin:

val manager = this.packageManager
val info = manager.getPackageInfo(this.packageName, PackageManager.GET_ACTIVITIES)
toast("PackageName = " + info.packageName + "\nVersionCode = "
            + info.versionCode + "\nVersionName = "
            + info.versionName + "\nPermissions = " + info.permissions)

Java:

PackageManager manager = this.getPackageManager();
PackageInfo info = manager.getPackageInfo(this.getPackageName(), PackageManager.GET_ACTIVITIES);
Toast.makeText(this,
     "PackageName = " + info.packageName + "\nVersionCode = "
       + info.versionCode + "\nVersionName = "
       + info.versionName + "\nPermissions = " + info.permissions, Toast.LENGTH_SHORT).show();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Merkidemis
  • 2,801
  • 2
  • 20
  • 26
  • 6
    Android's official description of `android:versionCode` and `android:versionName` can be found here: http://developer.android.com/tools/publishing/versioning.html#appversioning – Goffredo Jul 19 '12 at 17:30
  • 3
    **this** in this case is Context .ie Activity, Service .etc – Peter Chaula Jun 28 '17 at 06:28
  • 3
    when you paste some sample code is usefull to explain the meaning of the parameters.... althoug everybody can understand what `this.getPackageName()` represents the `0` you just spit there has no clue about the meaning – Rafael Lima Aug 02 '18 at 02:41
  • 1
    Android Studio claims versionCode is deprecated – Roman Gherta Apr 18 '19 at 21:43
  • 1
    @RomanGherta It is as of API 28. If you are writing code using anything less (or 8 years ago when this answer was written) you should still be good to go. Another answer here has the updated method. – Merkidemis May 01 '19 at 16:00
  • 1
    gives me a warning: "versionCode" is deprecated (on kotlin). What should I use instead? – gundrabur Mar 01 '20 at 16:43
158

Using Gradle and BuildConfig

Getting the VERSION_NAME from BuildConfig

BuildConfig.VERSION_NAME

Yep, it's that easy now.

Is it returning an empty string for VERSION_NAME?

If you're getting an empty string for BuildConfig.VERSION_NAME then read on.

I kept getting an empty string for BuildConfig.VERSION_NAME, because I wasn't setting the versionName in my Grade build file (I migrated from Ant to Gradle). So, here are instructions for ensuring you're setting your VERSION_NAME via Gradle.

File build.gradle

def versionMajor = 3
def versionMinor = 0
def versionPatch = 0
def versionBuild = 0 // Bump for dogfood builds, public betas, etc.

android {

  defaultConfig {
    versionCode versionMajor * 10000 + versionMinor * 1000 + versionPatch * 100 + versionBuild

    versionName "${versionMajor}.${versionMinor}.${versionPatch}"
  }

}

Note: This is from the masterful Jake Wharton.

Removing versionName and versionCode from AndroidManifest.xml

And since you've set the versionName and versionCode in the build.gradle file now, you can also remove them from your AndroidManifest.xml file, if they are there.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
  • 7
    This works great as long as you are accessing the BuildConfig from the application project, not a library used in the application project. Otherwise, you will get the BuildConfig for the library project, not the application. – John Cummings Dec 01 '15 at 21:46
  • @JohnCummings Interesting... didn't think of that. – Joshua Pinter Dec 02 '15 at 22:43
  • Not working at all, `versionName "1.2"`, and `BuildConfig.VERSION_NAME` return `empty`. API > 21 – Sojtin Aug 10 '16 at 11:55
  • As a follow-up, we actually stopped using this method in favour of just a static integer and a static String for the `versionCode` and `versionName`, respectively. Only because some tools like Code Push attempt to get your version number by parsing your `build.gradle` file and they can't full a dynamic value. – Joshua Pinter Mar 16 '18 at 15:56
  • @JoshuaPinter PackageManager really is the safest option. If you use version code overrides for splits BuildConfig constant still holds the original (albeit flavored) value. – Eugen Pechanec Apr 16 '18 at 14:26
  • I've used this solution but I've found the flaw. If you have `2.6.23` and the next you want update on `2.7.0` then you get versionCode less than early. Therefore I applied this: `versionCode versionMajor * 10000 + versionMinor * 100 + versionPatch` `versionPatch` is from 0 to 100 – 0x131313 Jan 28 '19 at 08:29
  • 2
    @JohnCummings it works if you `import com.package.name.BuildConfig;` or directly references it in code, even in a project lib ;) – SkyzohKey Jun 01 '21 at 12:56
61

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 the version name to a TextView
TextView tvVersionName = (TextView) findViewById(R.id.tv_versionName);
tvVersionName.setText(myVersionName);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Michael
  • 3,982
  • 4
  • 30
  • 46
  • 3
    Do you think that NNFE can be really thrown? It would be weird to not find a running application in the package manager :) – TWiStErRob Apr 16 '16 at 21:18
  • 1
    I'm with you that it might be weird, but it's the default exception of this method - see [API](http://developer.android.com/reference/android/content/pm/PackageManager.html#getPackageInfo%28java.lang.String,%20int%29): it says `Throws PackageManager.NameNotFoundException if a package with the given name can not be found on the system.`. However, I could not imagine a scenario for that! – Michael Apr 17 '16 at 08:50
59

Use the following to get the app version or build code which is used to identify the APK file by its version code. The version code is used to detect the actual build configuration at the time of update, publishing, etc.

int versionCode = BuildConfig.VERSION_CODE;

The version name is used to show the users or the developers of the development sequence. You can add any kind of version name as you want.

String versionName = BuildConfig.VERSION_NAME;
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Rohit Patil
  • 1,615
  • 12
  • 9
  • Out of all the answers, this is the simplest way. When you can do same thing with one line why do it with a 10+ lines of code. I don't understand that. – Amir Dora. Mar 15 '21 at 19:22
48

Kotlin one-liners

val versionCode = BuildConfig.VERSION_CODE
val versionName = BuildConfig.VERSION_NAME

Java one-liners

String versionCode = String.valueOf(BuildConfig.VERSION_CODE);
String versionName = String.valueOf(BuildConfig.VERSION_NAME);

Make sure to import BuildConfig into your class.

Gastón Saillén
  • 12,319
  • 5
  • 67
  • 77
37

Use the BuildConfig class:

String versionName = BuildConfig.VERSION_NAME;
int versionCode = BuildConfig.VERSION_CODE;

File build.gradle (app)

defaultConfig {
    applicationId "com.myapp"
    minSdkVersion 19
    targetSdkVersion 27
    versionCode 17
    versionName "1.0"
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Velayutham M
  • 1,119
  • 14
  • 18
25

As in 2020: As of API 28 (Android 9 (Pie)), "versionCode" is deprecated so we can use "longVersionCode".

Sample code in Kotlin

val manager = context?.packageManager
val info = manager?.getPackageInfo(
    context?.packageName, 0
)

val versionName = info?.versionName
val versionNumber = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                        info?.longVersionCode
                    } else {
                        info?.versionCode
                    }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mayank Sharma
  • 2,735
  • 21
  • 26
24

If you're using PhoneGap, then create a custom PhoneGap plugin:

Create a new class in your app's package:

package com.Demo; //replace with your package name

import org.json.JSONArray;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;

import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import com.phonegap.api.PluginResult.Status;

public class PackageManagerPlugin extends Plugin {

    public final String ACTION_GET_VERSION_NAME = "GetVersionName";

    @Override
    public PluginResult execute(String action, JSONArray args, String callbackId) {
        PluginResult result = new PluginResult(Status.INVALID_ACTION);
        PackageManager packageManager = this.ctx.getPackageManager();

        if(action.equals(ACTION_GET_VERSION_NAME)) {
            try {
                PackageInfo packageInfo = packageManager.getPackageInfo(
                                              this.ctx.getPackageName(), 0);
                result = new PluginResult(Status.OK, packageInfo.versionName);
            }
            catch (NameNotFoundException nnfe) {
                result = new PluginResult(Status.ERROR, nnfe.getMessage());
            }
        }

        return result;
    }
}

In the plugins.xml, add the following line:

<plugin name="PackageManagerPlugin" value="com.Demo.PackageManagerPlugin" />

In your deviceready event, add the following code:

var PackageManagerPlugin = function() {

};
PackageManagerPlugin.prototype.getVersionName = function(successCallback, failureCallback) {
    return PhoneGap.exec(successCallback, failureCallback, 'PackageManagerPlugin', 'GetVersionName', []);
};
PhoneGap.addConstructor(function() {
    PhoneGap.addPlugin('packageManager', new PackageManagerPlugin());
});

Then, you can get the versionName attribute by doing:

window.plugins.packageManager.getVersionName(
    function(versionName) {
        //do something with versionName
    },
    function(errorMessage) {
        //do something with errorMessage
    }
);

Derived from here and here.

Sean Hall
  • 7,629
  • 2
  • 29
  • 44
  • 11
    The question was not about PhoneGap. Your answer might just confuse people. – likebobby Jun 27 '12 at 15:53
  • 8
    @BobbyJ Nowhere in the question, title, or tags does it specify that the question was about a native application. This is what came up on google when I was searching for the answer, and would have saved me several hours. – Sean Hall Jun 27 '12 at 19:45
  • Thanks Hall72215. I'll be glad of this...if there really isn't any other way to get your own version number? I'd rather avoid a plugin if possible! – Magnus Smith Dec 10 '12 at 10:26
  • @MagnusSmith Not unless PhoneGap/Cordova has added it to their built in functions. – Sean Hall Dec 10 '12 at 13:35
  • 1
    In this example you can see how silly it is to use third party solutions to create apps. When you wrote it yourself from scratch it was just a couple of lines to code. – Codebeat May 20 '15 at 03:10
20

No, you don't need to do anything with AndroidManifest.xml

Basically, your app's version name and version code are inside the app level Gradle file, under defaultConfig tag:

defaultConfig {
   versionCode 1
   versionName "1.0"
}

Note: When you wish to upload an app to the play store, it can give any name as the version name, but the version code has to be different than the current version code if this app is already in the play store.

Simply use the following code snippet to get the version code & version name from anywhere in your app:

try {
    PackageInfo pInfo =   context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
    String version = pInfo.versionName;
    int verCode = pInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Monir Zzaman
  • 459
  • 4
  • 7
  • 2
    versionCode was deprecated in API 28. As stated in the docs, use longVersionCode instead; https://developer.android.com/reference/android/content/pm/PackageInfo.html#versionCode – Dan Abnormal Jan 31 '20 at 14:57
20

For API 28 (Android 9 (Pie)), the PackageInfo.versionCode is deprecated, so use this code below:

Context context = getApplicationContext();
PackageManager manager = context.getPackageManager();
try {
    PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
    myversionName = info.versionName;
    versionCode = (int) PackageInfoCompat.getLongVersionCode(info);
}
catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
    myversionName = "Unknown-01";
}
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Amir jodat
  • 569
  • 6
  • 13
16

version name : BuildConfig.VERSION_NAME version code : BuildConfig.VERSION_CODE

D.A.C. Nupun
  • 495
  • 5
  • 8
15

If you want to use it on XML content then add the below line in your Gradle file:

applicationVariants.all { variant ->
    variant.resValue "string", "versionName", variant.versionName
}

And then use it on your XML content like this:

<TextView
        android:gravity="center_horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/versionName" />
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Irfan Raza
  • 2,859
  • 1
  • 22
  • 29
  • 1
    I am getting in my xml the error: Cannot resolve symbol '@string/versionName' – RJB Sep 11 '19 at 17:55
15

There are two different scenarios in this question that are not properly addressed in any of the answers.

Scenario 1: You are not using modules

If you are not making use of modules, you can access your BuildConfig file and immeditally get your version code with:

val versionCode = BuildConfig.VERSION_CODE 

This is valid because this is your app level BuildConfig file and therefor it will contain the reference to your application version code

Scenario 2: Your app has many modules and you pretend to access the application version code from a lower module in your module hierarchy

It is normal for you to have many modules with a given hierarchy such as app -> data -> domain -> ui, etc. In this case, if you access the BuildConfig file from the "ui" module it will not give you a reference to the app version code but to the version code of that module.

In order to get the application version code you can use the given kotlin extension function.

First an extension function to get the PackageInfo

@Suppress("DEPRECATION")
fun Context.getPackageInfo(): PackageInfo {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        packageManager.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(0))
    } else {
        packageManager.getPackageInfo(packageName, 0)
    }
}

Extension function to get the version code

fun Activity.getVersionCode(): Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
    getPackageInfo().longVersionCode.toInt()
} else {
    getPackageInfo().versionCode
}

The approach for version name is similar:

fun Activity.getVersionName(): String = try {
    getPackageInfo().versionName
} catch (e: PackageManager.NameNotFoundException) {
    ""
}
Ricardo
  • 9,136
  • 3
  • 29
  • 35
14

For Xamarin users, use this code to get version name and code

  1. Version Name:

     public string getVersionName(){
         return Application.Context.ApplicationContext.PackageManager.GetPackageInfo(Application.Context.ApplicationContext.PackageName, 0).VersionName;
     }
    
  2. Version code:

     public string getVersionCode(){
         return Application.Context.ApplicationContext.PackageManager.GetPackageInfo(Application.Context.ApplicationContext.PackageName, 0).VersionCode;
     }
    
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tushar patel
  • 3,279
  • 3
  • 27
  • 30
10

Always do it with a try catch block:

String versionName = "Version not found";

try {
    versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
    Log.i(TAG, "Version Name: " + versionName);
} catch (NameNotFoundException e) {
    // TODO Auto-generated catch block
    Log.e(TAG, "Exception Version Name: " + e.getLocalizedMessage());
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
9

I have solved this by using the Preference class.

package com.example.android;

import android.content.Context;
import android.preference.Preference;
import android.util.AttributeSet;

public class VersionPreference extends Preference {
    public VersionPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        String versionName;
        final PackageManager packageManager = context.getPackageManager();
        if (packageManager != null) {
            try {
                PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
                versionName = packageInfo.versionName;
            } catch (PackageManager.NameNotFoundException e) {
                versionName = null;
            }
            setSummary(versionName);
        }
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shubham Gupta
  • 99
  • 1
  • 5
9

Here is the method for getting the version code:

public String getAppVersion() {
    String versionCode = "1.0";
    try {
        versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
    } catch (PackageManager.NameNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return versionCode;
}
wake-0
  • 3,918
  • 5
  • 28
  • 45
Gevaria Purva
  • 552
  • 5
  • 15
9

There are some ways to get versionCode and versionName programmatically.

  1. Get version from PackageManager. This is the best way for most cases.

     try {
         String versionName = packageManager.getPackageInfo(packageName, 0).versionName;
         int versionCode = packageManager.getPackageInfo(packageName, 0).versionCode;
     } catch (PackageManager.NameNotFoundException e) {
         e.printStackTrace();
     }
    
  2. Get it from generated BuildConfig.java. But notice, that if you'll access this values in library it will return library version, not apps one, that uses this library. So use only in non-library projects!

     String versionName = BuildConfig.VERSION_NAME;
     int versionCode = BuildConfig.VERSION_CODE;
    

There are some details, except of using second way in library project. In new Android Gradle plugin (3.0.0+) some functionalities removed. So, for now, i.e. setting different version for different flavors not working correct.

Incorrect way:

applicationVariants.all { variant ->
    println('variantApp: ' + variant.getName())

    def versionCode = {SOME_GENERATED_VALUE_IE_TIMESTAMP}
    def versionName = {SOME_GENERATED_VALUE_IE_TIMESTAMP}

    variant.mergedFlavor.versionCode = versionCode
    variant.mergedFlavor.versionName = versionName
}

Code above will correctly set values in BuildConfig, but from PackageManager you'll receive 0 and null if you didn't set version in default configuration. So your app will have 0 version code on device.

There is a workaround - set version for output apk file manually:

applicationVariants.all { variant ->
    println('variantApp: ' + variant.getName())

    def versionCode = {SOME_GENERATED_VALUE_IE_TIMESTAMP}
    def versionName = {SOME_GENERATED_VALUE_IE_TIMESTAMP}

    variant.outputs.all { output ->
        output.versionCodeOverride = versionCode
        output.versionNameOverride = versionName
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mohax
  • 4,435
  • 2
  • 38
  • 85
8

This code was mentioned above in pieces, but here it is again all included. You need a try/catch block, because it may throw a "NameNotFoundException".

try {
    String appVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
}
catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}

I hope this simplifies things for someone down the road. :)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jeff.H
  • 403
  • 4
  • 14
5

For someone who doesn’t need the BuildConfig information for application's UI, however wants to use this information for setting a CI job configuration or others, like me:

There is an automatically generated file, BuildConfig.java, under your project directory as long as you build your project successfully.

{WORKSPACE}/build/generated/source/buildConfig/{debug|release}/{PACKAGE}/BuildConfig.java

/**
* Automatically generated file. DO NOT MODIFY
*/
package com.XXX.Project;

public final class BuildConfig {
    public static final boolean DEBUG = Boolean.parseBoolean("true");
    public static final String APPLICATION_ID = "com.XXX.Project";
    public static final String BUILD_TYPE = "debug";
    public static final String FLAVOR = "";
    public static final int VERSION_CODE = 1;
    public static final String VERSION_NAME = "1.0.0";
}

Split information you need by a Python script or other tools. Here’s an example:

import subprocess
# Find your BuildConfig.java
_BuildConfig = subprocess.check_output('find {WORKSPACE} -name BuildConfig.java', shell=True).rstrip()

# Get the version name
_Android_version = subprocess.check_output('grep -n "VERSION_NAME" ' + _BuildConfig, shell=True).split('"')[1]
print('Android version: ’ + _Android_version)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JasonChiu
  • 171
  • 2
  • 6
4

First:

import android.content.pm.PackageManager.NameNotFoundException;

and then use this:

PackageInfo pInfo = null;
try {
     pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
} 
catch (NameNotFoundException e) {
     e.printStackTrace();
}

String versionName = pInfo.versionName;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
meduvigo
  • 1,523
  • 12
  • 7
4
package com.sqisland.android.versionview;

import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView textViewversionName = (TextView) findViewById(R.id.text);

    try {
        PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        textViewversionName.setText(packageInfo.versionName);

    }
    catch (PackageManager.NameNotFoundException e) {

    }
  }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Durul Dalkanat
  • 7,266
  • 4
  • 35
  • 36
4

Try this one:

try
{
    device_version =  getPackageManager().getPackageInfo("com.google.android.gms", 0).versionName;
}
catch (PackageManager.NameNotFoundException e)
{
    e.printStackTrace();
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
4

Kotlin example:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.act_signin)

    packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES).apply {
        findViewById<TextView>(R.id.text_version_name).text = versionName
        findViewById<TextView>(R.id.text_version_code).text =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) "$longVersionCode" else "$versionCode"
    }

    packageManager.getApplicationInfo(packageName, 0).apply{
        findViewById<TextView>(R.id.text_build_date).text =
            SimpleDateFormat("yy-MM-dd hh:mm").format(java.io.File(sourceDir).lastModified())
    }
}
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
  • Thank you, Alexander! I had the old BuildConfig code working in a project last year, but it's no longer working, so I used your code instead. Works like a charm. – Zonker.in.Geneva Aug 02 '21 at 08:45
3
private String GetAppVersion() {
    try {
        PackageInfo _info = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
        return _info.versionName;
    }
    catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return "";
    }
}

private int GetVersionCode() {
    try {
        PackageInfo _info = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
        return _info.versionCode;
    }
    catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return -1;
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Atif Mahmood
  • 8,882
  • 2
  • 41
  • 44
3

Example for inside Fragment usage.

import android.content.pm.PackageManager;
.......

private String VersionName;
private String VersionCode;
.......


Context context = getActivity().getApplicationContext();

/* Getting application version name and code */
try
{
     VersionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;

     /* I find it useful to convert vervion code into String,
        so it's ready for TextViev/server side checks
     */

     VersionCode = Integer.toString(context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode);
}
catch (PackageManager.NameNotFoundException e)
{
     e.printStackTrace();
}

// Do something useful with that
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
2
PackageInfo pinfo = null;
try {
    pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
}
catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}
int versionNumber = pinfo.versionCode;
String versionName = pinfo.versionName;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
janardhan
  • 39
  • 6
2

As I had to get only the version code and check whether the app was updated or not, if yes, I had to launch the play store to get an updated one. I did it this way.

public class CheckForUpdate {

    public static final String ACTION_APP_VERSION_CHECK = "app-version-check";

    public static void launchPlayStoreApp(Context context)
    {
        // getPackageName() from Context or Activity object
        final String appPackageName = context.getPackageName();
        try {
            context.startActivity(new Intent(Intent.ACTION_VIEW,
                                  Uri.parse("market://details?id=" + appPackageName)));
        }
        catch (android.content.ActivityNotFoundException anfe) {
            context.startActivity(new Intent(Intent.ACTION_VIEW,
                                  Uri.parse("https://play.google.com/store/apps/details?id=" +
                                             appPackageName)));
        }
    }

    public static int getRemoteVersionNumber(Context context)
    {
        int versionCode = 0;
        try {
            PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            String version = pInfo.versionName;
            versionCode = pInfo.versionCode;
        }
        catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }
}

Then I saved the version code using shared preference by creating a util class.

public class PreferenceUtils {

    // This is for version code
    private  final String APP_VERSION_CODE = "APP_VERSION_CODE";
    private  SharedPreferences sharedPreferencesAppVersionCode;
    private SharedPreferences.Editor editorAppVersionCode;
    private static Context mContext;

    public PreferenceUtils(Context context)
    {
        this.mContext = context;
        // This is for the app versioncode
        sharedPreferencesAppVersionCode = mContext.getSharedPreferences(APP_VERSION_CODE,MODE_PRIVATE);
        editorAppVersionCode = sharedPreferencesAppVersionCode.edit();
    }

    public void createAppVersionCode(int versionCode) {

        editorAppVersionCode.putInt(APP_VERSION_CODE, versionCode);
        editorAppVersionCode.apply();
    }

    public int getAppVersionCode()
    {
        return sharedPreferencesAppVersionCode.getInt(APP_VERSION_CODE,0); // As the default version code is 0
    }
}
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Ishwor Khanal
  • 1,312
  • 18
  • 30
1

Useful for build systems: there is a file generated with your APK file called output.json which contains an array of information for each generated APK file, including the versionName and versionCode.

For example,

[
    {
        "apkInfo": {
            "baseName": "x86-release",
            "enabled": true,
            "filterName": "x86",
            "fullName": "86Release",
            "outputFile": "x86-release-1.0.apk",
            "splits": [
                {
                    "filterType": "ABI",
                    "value": "x86"
                }
            ],
            "type": "FULL_SPLIT",
            "versionCode": 42,
            "versionName": "1.0"
        },
        "outputType": {
            "type": "APK"
        },
        "path": "app-x86-release-1.0.apk",
        "properties": {}
    }
]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tom
  • 6,946
  • 2
  • 47
  • 63
0

just write this.

xml code

<TextView
        android:id="@+id/appversion"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

initialize the variable for textview

TextView appversion;

set the textview id to variable

appversion = findViewById(R.id.appversion);

This is the main code to show the app version BuildConfig.VERSION_NAME just use it as string value

textview.setText("v"+BuildConfig.VERSION_NAME);
0

Very easy:

From Build

   val manufacturer = Build.MANUFACTURER
   val model = Build.MODEL
   val versionRelease = Build.VERSION.RELEASE

From BuildConfig

 val versionCode = BuildConfig.VERSION_CODE
 val versionName = BuildConfig.VERSION_NAME
AmirMohamamd
  • 301
  • 3
  • 14
0
    Log.e("TAG","VERSION.RELEASE {" + Build.VERSION.RELEASE + "}");
    Log.e("TAG","\nVERSION.INCREMENTAL {" + Build.VERSION.INCREMENTAL + "}");
    Log.e("TAG","\nVERSION.SDK {" + Build.VERSION.SDK + "}");
    Log.e("TAG","\nBOARD {" + Build.BOARD + "}");
    Log.e("TAG","\nBRAND {" + Build.BRAND + "}");
    Log.e("TAG","\nDEVICE {" + Build.DEVICE + "}");
    Log.e("TAG","\nFINGERPRINT {" + Build.FINGERPRINT + "}");
    Log.e("TAG","\nHOST {" + Build.HOST + "}");
    Log.e("TAG","\nID {" + Build.ID + "}");

thanks to https://stackoverflow.com/a/40421709/2828651

-1
try {
    PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
    String versionName = packageInfo.versionName;
    int versionCode = packageInfo.versionCode;
    //binding.tvVersionCode.setText("v" + packageInfo.versionName);
}
catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shanmugavel GK
  • 360
  • 2
  • 11