deleteNotificationChannel()

2021-10-24  本文已影响0人  安卓_背包客
/**Deletes the given notification channel.
*If you create a new channel with this same id, the deleted channel will be un-deleted with all of the *same settings it had before it was deleted.
**/
public void deleteNotificationChannel(String channelId)

在deleteNotificationChannel()需要注意,官方文档是这么描述的,“如果你新建的channel和要删除的channel是同一个channelId的话。新建的channel的属性会和要删除的那个channel是保持一致”,这意味着如果我们要动态修改通知声音的时候,创建的channelId不能相同,不然还是没有效果。

但是这里又有另外一个坑。你什么时候去删除呢?第一次测试我是在修改铃声或者振动的时候创建一个新的渠道,把之前所有旧的渠道都删除,但是这样会有一个bug,之前渠道上还在状态栏显示的Notification都会删除掉,所有要做一个判断,如果当前渠道在状态栏没有notification显示则删除,否则继续保存,代码如下:

 NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            List<NotificationChannel> channels = manager.getNotificationChannels();
            if (channels.size() == 0) {
                return;
            }
            for (int i = 0; i < channels.size(); i++) {
                NotificationChannel notificationChannel = channels.get(i);
                if (notificationChannel.getId() != null && !notificationChannel.getId().equals(String.valueOf(getChannelId()))) {
                   if (getActivieChannelConut(manager,String.valueOf(notificationChannel.getId()))==0)
                    manager.deleteNotificationChannel(getChannelId() + "");
                }
            }


        } else {
            manager.cancel(getChannelId());
        }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private int getActivieChannelConut(NotificationManager manager, String channeclid) {
        int cout = 0;
        StatusBarNotification[] activeNotifications = manager.getActiveNotifications();
        if (activeNotifications.length == 0) return cout;
        for (int i = 0; i < manager.getActiveNotifications().length; i++) {
            StatusBarNotification activeNotification = activeNotifications[i];
            if (activeNotification != null && !activeNotification.getNotification().getChannelId().equals(channeclid)) {
                cout++;
            }
        }
        return cout;
    }

如果需要通知静音,在创建Channel时,设置重要性Importance NotificationManager.IMPORTANCE_MIN,通知就是静默的状态。而设置NotificationManager.IMPORTANCE_HIGH,就是随系统使用声音或振动。

上一篇下一篇

猜你喜欢

热点阅读