Friday, March 23, 2012

How to get the current version of your application programatically in android?


How to get the current version of your application programatically in android?


Here is a sample code to get the version of your application in android.
Try changing the version in the AndroidManifest file and check the result in the console.
?
Drag and copy the code
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package pack.coderzheaven;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
public class GetVersionDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        int version_no = getVersionNumber(GetVersionDemo.this);
        System.out.println("Version Number : " + version_no);
    }
    public int getVersionNumber(Context context) {
        try {
            PackageInfo pInfo = context.getPackageManager().getPackageInfo("pack.coderzheaven", PackageManager.GET_META_DATA);
            return pInfo.versionCode;
        } catch (NameNotFoundException e) {
            return 0;
        }
    }
}

No comments: