android Notification总结
在发送一个Notification前,我们需要准备好一个NotificationManager
NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notification = new Notification();
1、定义一个Notification具备的三个基本参数icon,tickerText,以及添加打开关闭方式
notification.icon = R.drawable.ic_launcher;
notification.tickerText = "注意了,我被扔到状态栏了";
notification.flags = Notification.FLAG_AUTO_CANCEL;// 点击通知之后自动消失
notification.defaults=notification.DEFAULT_SOUND|notification.DEFAULT_VIBRATE; //notification被notify的时候,触发默认声音和默认震动
2、为notification添加一个意图(Intent):
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT);
notification.contentIntent = contentIntent;
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT);
notification.contentIntent = contentIntent;
由于Notification的包装内容为Intent,我们就可以方便地为通知被点击的触发的事件传值:
openintent.putExtra("isRead", true);
openintent.putExtra("name", "CaiYu");
4、发送通知
manager.notify(notifacation_id, notification);//notifacation_id由自己指定,为每一个Notification对应的唯一标志
5、自定义通知栏
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notify_view);//自定义的layout
contentView.setImageViewResource(R.id.notify_imageLog, R.drawable.ic_launcher);//layout中的控件
contentView.setTextViewText(R.id.notify_name, "1");
notification.contentView = contentView;
contentView.setImageViewResource(R.id.notify_imageLog, R.drawable.ic_launcher);//layout中的控件
contentView.setTextViewText(R.id.notify_name, "1");
notification.contentView = contentView;
6、删除、更改某些通知
manager.cancel(notifacation_id);
manager.cancelAll();
manager.notify(notifaction_id,newNotification);
7、用notification.builder实现
NotificationCompat.Builder builder = new Builder(context);
builder.setContent(remoteViews).setSmallIcon(R.drawable.icon).setLargeIcon(icon).setOngoing(true).setTicker("music is playing");
manager.notify(notifaction_id, builder.build());
builder.setContent(remoteViews).setSmallIcon(R.drawable.icon).setLargeIcon(icon).setOngoing(true).setTicker("music is playing");
manager.notify(notifaction_id, builder.build());