Sebastian Roth
Sebastian Roth

Reputation: 11537

Retrieve high resolution icon using PackageManager.getApplicationIcon

For a homescreen-like App I'm trying to collect the highest resolution App icons possible. The Homescreen will display the icons a little bigger and as such I need a high resolution icon.

This is my code:

final PackageManager pk = getPackageManager();
final String size;
try {
    Drawable d = pk.getApplicationIcon("com.mycompany.android.icontest");
    size = String.format("Width: %d, height: %d", d.getMinimumWidth(), d.getMinimumHeight());
} catch (PackageManager.NameNotFoundException e) {
    return;
}

This code will read the icon into a drawable. In that particular package 2 icons will be present, a res-hdpi icon & a res-xhdpi icon. Using the method above, only the HDPI version will be read.

How to read the XHDPI version by default?

Upvotes: 1

Views: 1878

Answers (1)

billyshieh
billyshieh

Reputation: 76

You can use getDrawableForDensity() to return a drawable object associated with a particular resource ID for the given screen density in DPI :

ActivityInfo info = packageManager.getActivityInfo(componentName, PackageManager.GET_META_DATA);

Resources resources;
try {
    resources = mPackageManager.getResourcesForApplication(
            info.applicationInfo);
} catch (PackageManager.NameNotFoundException e) {
    resources = null;
}

if (resources != null) {
    int iconId = info.getIconResource();
    if (iconId != 0) {
        Drawable d;
        try {
            d = resources.getDrawableForDensity(iconId, DisplayMetrics.DENSITY_XHIGH);
        } catch (Resources.NotFoundException e) {
            d = null;
        }
        return d;
    }
}

Upvotes: 6

Related Questions