今天看到EOE問答裡面有這“[Android 介面]NotificationManager 如何使用Bitmap做表徵圖”這樣一個問題,在論壇搜尋也沒有好的案例
特寫一個簡單的demo供大家參考
今天發布的是NotificationManager 使用Bitmap做表徵圖
關鍵code 複製代碼 代碼如下:public void notification(int flag)
{
Notification notification = new Notification();
//設定statusbar顯示的icon
notification.icon = R.drawable.icon;
//設定statusbar顯示的文字資訊
// myNoti.tickerText= new_msg ;
notification.flags = Notification.FLAG_AUTO_CANCEL;
//設定notification發生時同時發出預設聲音
notification.defaults = Notification.DEFAULT_SOUND;
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification);
Bitmap bitmap=null;
if(flag==0)
{
bitmap=drawableToBitmap(this.getResources().getDrawable(R.drawable.icon));
}else
{
//此處是關鍵地方,可以從網路或是sdcard上擷取圖片,轉成bitmap就可以
bitmap=drawableToBitmap(this.getResources().getDrawable(R.drawable.alert_dialog_icon));
}
contentView.setImageViewBitmap(R.id.notification_icon, bitmap);
contentView.setTextViewText(R.id.app_name, "Custom notification");
notification.contentView = contentView;
Intent intent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
notification.contentIntent = contentIntent;
//顯示Notification
Random random = new Random(new Date().getTime());
mNotificationManager.notify(random.nextInt(1000000), notification);
}
//轉化drawableToBitmap
public static Bitmap drawableToBitmap(Drawable drawable)
{
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
源碼下載:NotificationIcon.rar