huzhenjie
huzhenjie

Reputation: 33

Package manager has died while get versionCode in android

When I get the version code like:

public static int getVersionCode(Context context) {
    try {
        PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        return info.versionCode;
    } catch (Exception e) {
        return -1;
    }
}

Here is the trace when it happened:

java.lang.RuntimeException: Package manager has died
at android.app.ApplicationPackageManager.getPackageInfo(ApplicationPackageManager.java:78)

Upvotes: 2

Views: 1776

Answers (3)

Radhika Talaviya
Radhika Talaviya

Reputation: 1

Use

PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_META_DATA);

May this will work

Upvotes: 0

Rob Meeuwisse
Rob Meeuwisse

Reputation: 2937

I have similar code and it works correctly, so I don't understand why your's crashed and I am curious if you can find what caused the crash.

An alternative for you is to not look it up dynamically, but to get it from the build config.

public int getVersion(Context context) {
    return BuildConfig.VERSION_CODE;
}

Upvotes: 5

karan
karan

Reputation: 8853

try using the below code its old but I guess will work

public int getVersion(Context context) 
{
        try 
        {
            PackageInfo pInfo = context.getPackageManager().getPackageInfo("yourpackagename", PackageManager.GET_META_DATA);
            return pInfo.versionCode;
        } 
        catch (NameNotFoundException e) 
        {
            return 0;
        }
    }
}

Upvotes: -2

Related Questions