这是一个旧问题的新答案,只是为了将所有内容放在一个地方。您需要获取设备的默认密度,并调整图像大小以确保您具有正确一致的大小,因为仅请求图标并不总是返回正确的大小。
考虑这两种方法,一种是获取设备大小,另一种是调整可绘制对象的大小:
private int getDeviceDpi(){
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
return dm.densityDpi;
}
private Drawable getSizedAppIcon(Context context, String packageName, int Density) throws PackageManager.NameNotFoundException {
//for @param Density you can use a static from DisplayMetrics.<something>
PackageManager pm = Objects.requireNonNull(context).getPackageManager();
ApplicationInfo appInfo = this.getPackageManager().getApplicationInfo(packageName, 0);
Drawable icon = pm.getApplicationIcon(appInfo);
Bitmap bitmap = ((BitmapDrawable) icon).getBitmap();
switch (Density){
case DisplayMetrics.DENSITY_LOW: //120
return new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap,
32, 32, true));
case DisplayMetrics.DENSITY_MEDIUM: //160
return new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap,
48, 48, true));
case DisplayMetrics.DENSITY_HIGH: //240
return new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap,
72, 72, true));
case DisplayMetrics.DENSITY_XHIGH: //320
return new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap,
96, 96, true));
case DisplayMetrics.DENSITY_XXHIGH: //480
return new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap,
144, 144, true));
case DisplayMetrics.DENSITY_XXXHIGH: //640
return new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap,
192, 192, true));
default:
return icon;
}
}
然后像在这个例子中那样调用它们:
try{
getSizedAppIcon(this, "com.example.app",getDeviceDpi());
}catch (Exception ignore) {}