Honeycomb notifications - How to set largeIcon to

2019-01-13 07:15发布

问题:

I find myself curious why the setLargeIcon method on Notification.Builder only accepts a Bitmap, with no overload to provide a resource id. Perhaps it was done for performance reasons, but it seems odd as setSmallIcon does accept a res drawable id.

Notification.Builder builder = new Notification.Builder(application);
// ....
builder.setLargeIcon(iconBitmap);  // Requires a Bitmap
builder.setSmallIcon(iconResId);   // Requires a drawable resource ID
Notification notification = builder.getNotification();

Sadly the bitmap provided is not scaled in the notification, so the Bitmap needs to be provided exactly the right size for the notification view.

Assuming I need to provide xhdpi, hdpi, mdpi and ldpi versions of the largeIcon bitmap, what sizes do they need to be? I can see no mention in the docs, or after scouring the wider web.

回答1:

Not had a chance to check it yet but API 11 introduced the following public dimens:

  • notification_large_icon_height
  • notification_large_icon_width

Should be able to use those to scale your image before setting it on the notification.



回答2:

I used the dimensions of the notification's large icon to create a scaled bitmap

BitmapDrawable contactPicDrawable = (BitmapDrawable) ContactsUtils.getContactPic(mContext, contactId);
Bitmap contactPic = contactPicDrawable.getBitmap();

Resources res = mContext.getResources();
int height = (int) res.getDimension(android.R.dimen.notification_large_icon_height);
int width = (int) res.getDimension(android.R.dimen.notification_large_icon_width);
contactPic = Bitmap.createScaledBitmap(contactPic, width, height, false); 

And then I set the large icon with this scaled bitamp.