Android 8.0
今天正式发布了,你还在用哪个版本呢?
言归正传,本次更新了不少内容,这篇为你介绍如何创建 通知渠道 & 通知角标
如果你开启了 NotificationChannel
则在 Android 8.0 的设置中,可以看到这样的内容:
可以看出 NotificationChannel
其实是把 Notification
分了个类别,设置不同优先级,开关之类的。如果你的 app 适配了的话,用户可以关掉不喜欢的通知,以提高用户体验。
创建 NotificationChannel
通过 NotificationManager 的 createNotificationChannel 方法来创建 NotificationChannel 。
1 | public void createNotificationChannel(String id, String name, int importance, String desc) { |
NotificationChannel 的方法列表:
- getId() — 获取 ChannleId
- enableLights() — 开启指示灯,如果设备有的话。
- setLightColor() — 设置指示灯颜色
- enableVibration() — 开启震动
- setVibrationPattern() — 设置震动频率
- setImportance() — 设置频道重要性
- getImportance() — 获取频道重要性
- setSound() — 设置声音
- getSound() — 获取声音
- setGroup() — 设置 ChannleGroup
- getGroup() — 得到 ChannleGroup
- setBypassDnd() — 设置绕过免打扰模式
- canBypassDnd() — 检测是否绕过免打扰模式
- getName() — 获取名称
- setLockScreenVisibility() — 设置是否应在锁定屏幕上显示此频道的通知
- getLockscreenVisibility() — 检测是否应在锁定屏幕上显示此频道的通知
- setShowBadge() 设置是否显示角标
- canShowBadge() — 检测是否显示角标
setImportance 重要程度
越高,提示权限就越高,最高的支持发出声音&悬浮通知。
1 | public static final int IMPORTANCE_DEFAULT = 3; |
删除 NotificationChannel
通过 NotificationManager 的 deleteNotificationChannel 方法来删除 NotificationChannel 。
1 | mNotificationManager.deleteNotificationChannel(chatChannelId); |
发出通知
只需要设置一个 ChannelId 即可发布到对应的 Channel 上,需要注意的是 NotificationChannel 一定要先创建才行。
1 | Notification.Builder builder = new Notification.Builder(this, chatChannelId); |
显示角标
首先要开启允许使用通知圆点,这个是用户可以取消的,如果你要显示一定要代码中保证是开启状态。
NotificationChannel 开启角标
1 | notificationChannel.setShowBadge(true); |
Notification 设置角标样式
1 | new Notification.Builder(this, chatChannelId).setBadgeIconType(BADGE_ICON_SMALL) |
Notification 设置角标计数
1 | new Notification.Builder(this, chatChannelId).setNumber(1) |
跳转到设置
1 | Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS); |
使用 NotificationChannleGroup
如果你的通知渠道比较多,那么久可以考虑使用 NotificationChannleGroup
来管理一下
创建 NotificationChannleGroup
和创建 NotificationChannle 类似
1 | mNotificationManager.createNotificationChannelGroup(new NotificationChannelGroup(groupId, groupName)); |
NotificationChannle 绑定 groupId
1 | notificationChannel.setGroup(groupId); |
删除 NotificationChannleGroup
可以批量删除该 Group 下的所有 Channel
1 | mNotificationManager.deleteNotificationChannelGroup(groupId2); |