检索方法从PackageManger xhdpi应用程序图标?应用程序、图标、方法、xhdpi

2023-09-13 01:17:56 作者:对你有所谓

我在我的应用程序,其中,生成所有已安装的应用程序的一个ListView的活动。除了该应用名称,应用程序图标显示为好。我已经创建了一个包含这中间的图标一切有关应用程序的信息,对象的数组,并使用检索到的图标:

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);

其中,应用程序< PackageInfo> 对象。这样做的问题是,虽然我随时可以访问所有的可绘制各种应用程序似乎拉各种质量可绘制;一个应用程序图标会非常高清晰度,而另一个将是低分辨率的版本。我本来以为的code以上的行会占到屏幕尺寸和找到合适的图标,但事实并非如此。是否有占屏幕尺寸的方法吗?甚至更多preferably是有办法只提取最高的水库图标,然后将其向下根据屏幕大小的规模,这将基本上保证所有的人看起来干净?

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?

编辑:我已经找到了解决方案,但它仅适用于Android的4.0 +

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();
}

有关他人的引用,这个工程,如果有人为Android的老版本,将是非常有帮助的解决方案。

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

推荐答案

我怀疑有一些其他的原因,为什么图标看起来很糟糕(如在你的应用程序调整),但如果你需要做任何Android版本:

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);