如何发送一个通知?
Android 8版本之前:
第一步:获取NotificationManager
mNotificationManager = (NotificationManager)activity.getSystemService(NOTIFICATION_SERVICE);
第二步:构建一个Notification的builder用于构建Notification
Notification.Builder builder=new Notification.Builder(activity);
builder.setContentTitle("测试 "+mNotificationId) //必须提供
.setContentText("测试内容") //必须提供
.setTicker("测试通知到达")
.setWhen(System.currentTimeMillis())
.setPriority(Notification.PRIORITY_DEFAULT)//设置该通知优先级
.setSmallIcon(R.mipmap.ic_launcher_round) //必须提供
.setOngoing(true) // 设置常驻用户无法清除
.setContentIntent(intent); //用于点击通知跳转界面
第三步:调用NotificationManager的notify函数,传入一个int类型id(用于标识通知)和一个Notification对象
mNotificationManager.notify(mNotificationId++, builder.build());
Android 8版本之后:
大体步骤没什么区别,多了个Channel通道
mNotificationManager = (NotificationManager) activity.getSystemService(NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,"my_channel",NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true); //是否在桌面icon右上角展示小红点
channel.setLightColor(Color.GREEN); //小红点颜色
channel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
mNotificationManager.createNotificationChannel(channel);//创建Channel
builder需要设置Channel
builder.setContentTitle("测试 "+mNotificationId) //必须提供
.setContentText("测试内容") //必须提供
.setTicker("测试通知到达")
.setWhen(System.currentTimeMillis())
.setPriority(Notification.PRIORITY_DEFAULT)//设置该通知优先级
.setSmallIcon(R.mipmap.ic_launcher_round) //必须提供
.setOngoing(true) // 设置常驻用户无法清除
.setContentIntent(intent) //用于点击通知跳转界面
.setChannelId(CHANNEL_ID); //Android O以上版本必须提供
</