Notification:通知信息类,它里面对应了通知栏的各个属性
NotificationManager:是状态栏通知的管理类,负责发通知、清除通知等操作。
使用流程:
①获取NotificationManager
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
②Android8.0引入了通知渠道 创建notification对象时需要传入对应的channelId
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("channelId", "一个通知", NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(channel);
}
③使用Builder构造器创建Notification对象 传入的channelId一定要一致
Notification notification = new NotificationCompat.Builder(this, "channelId")
④添加通知的一些属性
notification = new NotificationCompat.Builder(this, "channelId")
.setContentTitle("通知")
.setContentText("赶紧学习啊")
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.import))
.build();
⑤触发通知
manager.notify(1, notification);
⑥使用setContentIntent()设置 需要传入的PendingIntent如下
Intent intent = new Intent(this, NotificationActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
notification = new NotificationCompat.Builder(this, "channel")
.setContentTitle("通知")
.setContentText("赶紧学习呀")
.setSmallIcon(R.drawable.ic_insert_emoticon_black_24dp)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
.setColor(Color.parseColor("#000fff"))
.setContentIntent(pendingIntent)
.build();
⑦取消通知的两种方法
添加 .setAutoCancel(true) 或者触发 manager.cancel(1); //cancel内传入的id需要与notify传入的id值相同
通知重要程度设置,NotificationManager类中
- IMPORTANCE_NONE 关闭通知
- IMPORTANCE_MIN 开启通知,不会弹出,不发出提示音,状态栏中无显示
- IMPORTANCE_LOW 开启通知,不会弹出,不发出提示音,状态栏中显示
- IMPORTANCE_DEFAULT 开启通知,不会弹出,发出提示音,状态栏中显示
- IMPORTANCE_HIGH 开启通知,会弹出,发出提示音,状态栏中显示
常见方法
- setContentTitle(String string) 设置标题
- setContentText(String string) 设置文本内容
- setSmallIcon(int icon) 设置小图标
- setLargeIcon(Bitmap icon) 设置通知的大图标
- setColor(int argb) 设置小图标的颜色
- setContentIntent(PendingIntent intent) 设置点击通知后的跳转意图
- setAutoCancel(boolean boolean) 设置点击通知后清除通知
- setWhen(long when) 设置通知被创建的时间