广播通知收发

更新时间: 2024/09/13 14:33:28

本文介绍通过网易云信即时通讯 IM SDK(以下简称 NIM SDK)接收广播通知的技术原理、实现流程。

技术原理

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

前提条件

根据本文操作前,请确保您已经实现了以下设置:

  • 前往 网易云信控制台,为应用开通即时通讯产品,并开通 全局功能 > 全员广播 功能。
  • 登录 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
    C++V2NIMNotificationListener notificationListener;
    notificationListener.onReceiveCustomNotifications = [=](nstd::vector<V2NIMCustomNotification> customNotifications) {
        // process custom notifications
    };
    notificationListener.onReceiveBroadcastNotifications = [=](nstd::vector<V2NIMBroadcastNotification> broadcastNotifications) {
        // process broadcast notifications
    };
    v2::V2NIMClient::get().getNotificationService().addNotificationListener(notificationListener);
    
    Web/uni-app/小程序
    TypeScriptnim.V2NIMNotificationService.on("onReceiveCustomNotifications", function (customNotification: V2NIMCustomNotification[]) {}) // 广播通知接收回调
    nim.V2NIMNotificationService.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 回调事件,通知接收方接收广播通知。

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