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 obje
Here's a new answer to an old question, just to put everything in one place. You'll need to get the devices default density, and resize the image to ensure that you have a properly conforming size, as just requesting the icon does not always return proper size.
Consider these two methods, one to obtain device size, and the second to resize your drawable:
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.
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;
}
}
Then call them like in this example:
try{
getSizedAppIcon(this, "com.example.app",getDeviceDpi());
}catch (Exception ignore) {}