广播通知收发

更新时间: 2024/04/17 15:00:36

本文介绍通过 NetEase IM SDK(以下简称 NIM SDK) 接收广播通知的技术原理、实现流程。

技术原理

广播通知由云信 IM 服务端 API 发送广播消息发起,SDK 接收到广播通知后通知应用层,并对应用内所有用户发送一条广播通知。

前提条件

  • 广播通知功能需要单独开通,进行相关开发前,请确保您已在云信控制台 IM 即时通讯下开通全局功能 > 全员广播功能。
  • 登录 IM。未登录 IM 的用户接收不到广播消息。

使用限制

  • SDK 不支持发送广播通知,仅支持通过服务端 API 发送,且一个应用一分钟最多发起 10 次,一天最多发起 1000 次,超出频控会返回 416 错误码。如需修改服务端频控请至云信控制台 IM 即时通讯下的服务端频控 > 发送广播消息进行编辑修改。
  • 广播通知不支持本地存储、第三方推送、漫游和生成会话。
  • 最多保留最近 100 条离线广播通知。

实现流程

  1. 通知接收方监听广播通知接收回调。

    注册系统通知监听器的广播通知接收事件 onReceiveBroadcastNotifications

    Android

    若自定义的系统通知需要作用于全局,不依赖某个特定的 Activity,那么需要提前在 Application 的 onCreate 中调用该监听接口。

    javaV2NIMNotificationService v2NotificationService = NIMClient.getService(V2NIMNotificationService.class);
    
    V2NIMNotificationListener notificationListener = new V2NIMNotificationListener() {
        @Override
        public void onReceiveCustomNotifications(List<V2NIMCustomNotification> customNotifications) {
        // your code      
        }
    
        @Override
        // 广播通知接收回调
        public void onReceiveBroadcastNotifications(List<V2NIMBroadcastNotification> broadcastNotifications) {
        // your code
        }
    };
    
    v2NotificationService.addNotificationListener(notificationListener);
    
    iOS
    objective-c// listener 实现 V2NIMNotificationListener 协议
    [[[NIMSDK sharedSDK] v2NotificationService] addNoticationListener:listener]
    
    macOS/Windows
    cppV2NIMNotificationListener listener;
    listener.onReceiveCustomNotifications = [](nstd::vector<V2NIMCustomNotification> customNotifications) {
        // handle custom notifications
    };
    // 广播通知接收回调
    listener.onReceiveBroadcastNotifications = [](nstd::vector<V2NIMBroadcastNotification> broadcastNotifications) {
        // handle broadcast notifications
    };
    notificationService.addNotificationListener(listener);
    
    Web/uni-app/小程序
    typescriptnim.V2NIMMessageService.on("onReceiveCustomNotifications", function (customNotification: V2NIMCustomNotification[]) {})
    // 广播通知接收回调
    nim.V2NIMMessageService.on("onReceiveBroadcastNotifications", function (broadcastNotification: V2NIMBroadcastNotification[]) {})
    
    Harmony
    typescriptnim.messageService.on("onReceiveCustomNotifications", function (customNotification: V2NIMCustomNotification[]) {})
    // 广播通知接收回调
    nim.messageService.on("onReceiveBroadcastNotifications", function (broadcastNotification: V2NIMBroadcastNotification[]) {})
    
  2. 通知发送方调用新版服务端 API 发送一条广播通知。

  3. SDK 触发 onReceiveBroadcastNotifications 回调事件,通知接收方接收广播通知。

此文档是否对你有帮助?
有帮助
去反馈
  • 技术原理
  • 前提条件
  • 使用限制
  • 实现流程