Tuesday, 27 August 2013

How to get App VersionCode and VersionName in Android


How to get App VersionCode and VersionName in Android

This is very simple task, you can use the android:versionCode and android:versionName attributes in the AndroidManifest.xml. That way, as long as the package name is the same it won't overlap and you can get that info like this to see if there is a newer version available.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
         package="com.itdeveloper.TestApp"
         android:versionCode="6"
         android:versionName="1.2.2">

Then you can read these values and compare with values on your server, like this.

try {
       PackageManager manager = context.getPackageManager();
       PackageInfo info = manager.getPackageInfo(context.getPackageName(),0);
                     int code = info.versionCode;
                     String name = info.versionName;
       // Compare with values on the server to see if there is a new version
    } catch (NameNotFoundException e) {
                     e.printStackTrace();
    }

If you're checking for the version of the same app, you can replace the hard-coded package name with context.getPackageName().
Like
PackageInfo info = manager.getPackageInfo(context.getPackageName(),0);


Happy Codddddding J

No comments:

Post a Comment