Notification详解
Notification的使用步骤
//1.获取NotificationManager
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//2.设置消息频道
String id = "my_channel_01";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel(id,"name",importance);
mChannel.enableLights(true);
mNotificationManager.createNotificationChannel(mChannel);
//3.创建NotificationCompat.Builder
Notification.Builder notification = new Notification.Builder(MainActivity.this , id)
.setContentTitle("Title")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("主要内容");
//4.(可选步骤)设置点击通知栏里信息的事件
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this,Activity2.class), PendingIntent.FLAG_CANCEL_CURRENT);
notification.setContentIntent(contentIntent);
//5.发布通知消息
int notifyId=2;
mNotificationManager.notify(notifyId, notification.build());
自定义Notification样式
//自定义Notification样式布局
RemoteViews remoteViews=new RemoteViews("com.top.notification",R.layout.notification_layout);
//1.获取NotificationManager
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//2.设置消息频道
String id = "my_channel_01";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel(id,"name",importance);
mChannel.enableLights(true);
mNotificationManager.createNotificationChannel(mChannel);
//3.创建NotificationCompat.Builder
Notification.Builder notification = new Notification.Builder(MainActivity.this , id)
.setContentTitle("Title")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("主要内容")
.setContent(remoteViews); //主要多了这个!!!!!
//4.发布通知消息
int notifyId=2;
mNotificationManager.notify(notifyId, notification.build());
自定义Notification样式里控件的点击事件
//举个例子,音乐播放器的通知栏里的控制播放事件,可以通过发送一个广播或者启动服务,通过判断Intent来确定是啥事件
PendingIntent pendingIntent=PendingIntent.getService(this,
requestzCode,
new Intent(this,BroadCastReceiverdemo.class),
flags);
remoteViews.setOnClickPendingIntent(R.id.btn_notification,pendingIntent);
网友评论