Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

android - Retrieving xhdpi app icons from packageManager?

I have an activity in my app wherein a ListView of all installed apps is generated. In addition to the app name, the app icon appears as well. I had created an array of objects containing all the information about the application, among this the icon, and retrieved the icon using:

drawableAppIcon = mPackageManager.getApplicationIcon(apps.applicationInfo);

Where application is a <PackageInfo> object. The problem with this is that while I readily have access to all the drawables, various apps seem to pull various quality drawables; one app icon will be extremely high res while another will be the low res version. I would have thought that the above line of code would have accounted for screen size and found the appropriate icons, but it doesn't. Is there an alternative that accounts for screen size? Or even more preferably is there a way to extract just the highest res icon and then scale it down based on screen size, which would basically guarantee all of them look clean?

EDIT: I've found a solution, but it only works for Android 4.0+

try {
    Context otherAppCtxt = context.createPackageContext(apps.applicationInfo.packageName, Context.CONTEXT_IGNORE_SECURITY);
    info.drawableAppIcon = otherAppCtxt.getResources().getDrawableForDensity(apps.applicationInfo.icon, DisplayMetrics.DENSITY_XHIGH);
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}

For others' reference, this works, if someone has a solution for older version of Android that would be really helpful.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I suspect there is some other reason why the icons look bad (such as resizing within your app), but if you need to do it for any Android version:

// Get the application's resources
Resources res = mPackageManager.getResourcesForApplication(appInfo);

// Get a copy of the configuration, and set it to the desired resolution
Configuration config = res.getConfiguration();
Configuration originalConfig = new Configuration(config);
config.densityDpi = DisplayMetrics.DENSITY_XHIGH;

// Update the configuration with the desired resolution
DisplayMetrics dm = res.getDisplayMetrics();
res.updateConfiguration(config, dm);

// Grab the app icon
Drawable appIcon = res.getDrawable(appInfo.icon);

// Set our configuration back to what it was
res.updateConfiguration(originalConfig, dm);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...