美文网首页
鸿蒙+next+接入推送服务

鸿蒙+next+接入推送服务

作者: flfljh | 来源:发表于2024-10-29 19:49 被阅读0次

鸿蒙 next 推送服务接入

1.开通推送服务

按照官方文档开通推送服务: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/push-config-setting-V5

2.配置 client_id

entry/src/main/module.json5 配置新增 metadata client_id, 该值在鸿蒙后台AppGallery Connect中找到常规→应用→Client Id

{
 "module": { 
    "metadata": [
      {
        "name": "client_id",
        "value": "xxxxxxxx"
      }
    ],
 }
}

3.获取 华为推送 token 并且上报token 到自己的应用服务器

static async setPushToken() {
    //   关联华为推送 token
    PushMsgUtils.getPushToken((token) => {
      BaseApi.setToken({
        "token": token
      }).then(res => {
        if (res['code'] == 200) {
          LogUtil.info('BaseApi.setToken success');
        }
      })
    })
  }

  static async getPushToken(success: (token: string) => void) {
    pushService.getToken().then((data: string) => {
      success(data)
      LogUtil.info('Succeeded in getting push token:', data);
    }).catch((err: BusinessError) => {
      LogUtil.error(`Failed to get push token: ${err.code} ${err.message}`);
    });
  }

4.在应用进入首页时申请允许通知权限.

static requestPermission(context: common.UIAbilityContext) {
    // 申请权限
    notificationManager.isNotificationEnabled().then((data: boolean) => {
      console.info("run isNotificationEnabled success, data: " + data);
      if (!data) {
        notificationManager.requestEnableNotification(context).then(() => {
          console.info(`run requestEnableNotification success`);
        }).catch((err: BusinessError) => {
          if (1600004 == err.code) {
            console.error(
              `run requestEnableNotification refused, code is ${err.code}, message is ${err.message}`);
          } else {
            console.error(
              `run requestEnableNotification failed, code is ${err.code}, message is ${err.message}`);
          }
        });
      }
    }).catch((err: BusinessError) => {
      console.error(`run isNotificationEnabled fail: ${JSON.stringify(err)}`);
    });
  }

5.新增 skills 配置

entry/src/main/module.json5 找到启动 Ability 的 skills 配置,注意默认skills会有一项,千万不要删除,要在尾部添加一条, actions 设置为空字符串表示不实用actions。

 {
            "actions": [
              "" 
            ],
            "uris": [
              {
                "scheme": "https",
                "host": "xxx.xxxx.com", //自己的域名
                "path": "test"
              }
            ]
          } // 新增一个skill对象,配置actions和uris用于其他业务场景

6.测试推送通知可以准确到达用户设备

6.1 使用鸿蒙后台的添加推送通知功能:

该功能是测试的后台接口调用推送

[图片上传失败...(image-4ea4a4-1730288932825)]

6.2 使用设备本地代码推送功能

// 本地发布普通文本通知
  static localPublishBasic(params: LocalPublishBasicParams) {
    // 通过WantAgentInfo的operationType设置动作类型
    let wantAgentInfo: wantAgent.WantAgentInfo = {
      wants: [
        {
          deviceId: '',
          bundleName: 'com.xxxxx.xxxx', // 应用包名
          abilityName: 'EntryAbility',
          action: '',
          entities: [],
          uri: "https://xxx.xxxx.com/test",
          parameters: {
            page: params.page,
          }
        }
      ],
      operationType: wantAgent.OperationType.START_ABILITY,
      requestCode: 0,
      wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
    };

    // 创建WantAgent
    wantAgent.getWantAgent(wantAgentInfo, (err: BusinessError, data: WantAgent) => {
      if (err) {
        console.error(`Failed to get want agent. Code is ${err.code}, message is ${err.message}`);
        return;
      }
      console.info('Succeeded in getting want agent.');
      let notificationRequest: notificationManager.NotificationRequest = {
        id: 1,
        content: {
          notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
          normal: {
            title: params.title,
            text: params.content,
          },
        },
        notificationSlotType: notificationManager.SlotType.SOCIAL_COMMUNICATION,
        wantAgent: data,
      };

      notificationManager.publish(notificationRequest, (err: BusinessError) => {
        if (err) {
          console.error(`Failed to publish notification. Code is ${err.code}, message is ${err.message}`);
          return;
        }
        console.info('Succeeded in publishing notification.');
      });
    });
  }

7.处理用户点击推送消息事件

事件会在 Ability 的 onNewWantonCreate中触发:

情况1:应用未启动,走 UIAbility 的 onCreate(want: Want)
情况2:应用启动了,在前台或后台,走 UIAbility 的 onNewWant(want: Want)

根据以上信息,封装一个统一的消息处理方法:

interface MessageReceivedParams {
  want?: Want
  method: "onCreate" | "onNewWant" | "enterDnTabBarPage"
}

static messageReceived(params: MessageReceivedParams) {
    if (params.want && params.want.uri && params.want.uri.length > 0) {
      LogUtil.info(`run messageReceived ${params.method}:`, JSON.stringify(params.want))
      const routePae = params.want.parameters?.['page'] as string;
      const proctolObj = Utils.parseProtoclUrl(routePae);
      if (params.method == "onNewWant") {
        // 应用启动了,在前台或后台,走 UIAbility 的 onNewWant(want: Want)
        if (routePae) {
          PushMsgUtils._messageJump(proctolObj)
        } else {
          LogUtil.error("无跳转页面:page传参")
        }

      } else if (params.method == "onCreate") {
        //  应用未启动,走 UIAbility 的 onCreate(want: Want)
        if (routePae) {
          GlobalContext.getContext().setObject("messageReceived", proctolObj)
        }
      }
    }

    if (params.method == "enterDnTabBarPage") {
      // 走onCreate后初始化完成进入DnTabBarPage页
      const messageReceived = GlobalContext.getContext().getObject("messageReceived")
      if (messageReceived) {
        GlobalContext.getContext().deleteObject("messageReceived")
        PushMsgUtils._messageJump(messageReceived as ProctolObjType)
      }
    }
  }

8.完整代码参考:

将上述逻辑统一封装成了 PushMsgUtils ,根据自己的需求修改使用:

import { pushService } from '@kit.PushKit';
import { notificationManager } from '@kit.NotificationKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { common, Want, WantAgent, wantAgent } from '@kit.AbilityKit';
import BaseApi from '../../http/action/BaseApi';
import { router } from '@kit.ArkUI';
import { GlobalContext } from './GlobalContext';
import { LogUtil } from './LogUtil';
import Utils, { ProctolObjType } from './Utils';

interface MessageReceivedParams {
  want?: Want
  method: "onCreate" | "onNewWant" | "enterDnTabBarPage"
}

interface LocalPublishBasicParams {
  page: string // 跳转页面
  title: string // 标题
  content: string // 内容
}

export default class PushMsgUtils {
  static requestPermission(context: common.UIAbilityContext) {
    // 申请权限
    notificationManager.isNotificationEnabled().then((data: boolean) => {
      console.info("run isNotificationEnabled success, data: " + data);
      if (!data) {
        notificationManager.requestEnableNotification(context).then(() => {
          console.info(`run requestEnableNotification success`);
        }).catch((err: BusinessError) => {
          if (1600004 == err.code) {
            console.error(
              `run requestEnableNotification refused, code is ${err.code}, message is ${err.message}`);
          } else {
            console.error(
              `run requestEnableNotification failed, code is ${err.code}, message is ${err.message}`);
          }
        });
      }
    }).catch((err: BusinessError) => {
      console.error(`run isNotificationEnabled fail: ${JSON.stringify(err)}`);
    });
  }

  static async setPushToken() {
    //   关联华为推送 token
    PushMsgUtils.getPushToken((token) => {
      BaseApi.setToken({
        "token": token
      }).then(res => {
        if (res['code'] == 200) {
          LogUtil.info('BaseApi.setToken success');
        }
      })
    })
  }

  static async getPushToken(success: (token: string) => void) {
    pushService.getToken().then((data: string) => {
      success(data)
      LogUtil.info('Succeeded in getting push token:', data);
    }).catch((err: BusinessError) => {
      LogUtil.error(`Failed to get push token: ${err.code} ${err.message}`);
    });
  }


  private static _messageJump(proctolObj: ProctolObjType) {
    let jumpType = parseInt(proctolObj.params['type'] as string)
    if (jumpType == 1) {
      // 跳转应用内页面
      router.pushUrl({
        url: proctolObj.pathName,
        params: proctolObj.params
      })
    } else if (jumpType == 2) {
      //内嵌H5页面
      LogUtil.info("内嵌H5页面")
    } else if (jumpType == 3) {
      // 微信小程序
      const appId = proctolObj.params['appId'] as string;
      LogUtil.info("微信小程序", appId)

    } else if (jumpType == 4) {
      // 浏览器
      Utils.toWebBrowser(proctolObj.originUrl)
    } else if (jumpType == 5) {
      // 打开App或去下载App
      Utils.toAppGalleryDetail("com.qxhms.senioriup")
    } else if (jumpType == 6) {
      // 添加QQ群
    }
  }

  /*
   *参考: https://blog.csdn.net/fwt336/article/details/139465587
   */
  static messageReceived(params: MessageReceivedParams) {
    if (params.want && params.want.uri && params.want.uri.length > 0) {
      LogUtil.info(`run messageReceived ${params.method}:`, JSON.stringify(params.want))
      const routePae = params.want.parameters?.['page'] as string;
      const proctolObj = Utils.parseProtoclUrl(routePae);
      if (params.method == "onNewWant") {
        // 应用启动了,在前台或后台,走 UIAbility 的 onNewWant(want: Want)
        if (routePae) {
          PushMsgUtils._messageJump(proctolObj)
        } else {
          LogUtil.error("无跳转页面:page传参")
        }

      } else if (params.method == "onCreate") {
        //  应用未启动,走 UIAbility 的 onCreate(want: Want)
        if (routePae) {
          GlobalContext.getContext().setObject("messageReceived", proctolObj)
        }
      }
    }

    if (params.method == "enterDnTabBarPage") {
      // 走onCreate后初始化完成进入DnTabBarPage页
      const messageReceived = GlobalContext.getContext().getObject("messageReceived")
      if (messageReceived) {
        GlobalContext.getContext().deleteObject("messageReceived")
        PushMsgUtils._messageJump(messageReceived as ProctolObjType)
      }
    }
  }

  // 本地发布普通文本通知
  static localPublishBasic(params: LocalPublishBasicParams) {
    // 通过WantAgentInfo的operationType设置动作类型
    let wantAgentInfo: wantAgent.WantAgentInfo = {
      wants: [
        {
          deviceId: '',
          bundleName: 'com.xxxx.xxxx',
          abilityName: 'EntryAbility',
          action: '',
          entities: [],
          uri: "https://xxx.xxxx.com/test",
          parameters: {
            page: params.page,
          }
        }
      ],
      operationType: wantAgent.OperationType.START_ABILITY,
      requestCode: 0,
      wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
    };

    // 创建WantAgent
    wantAgent.getWantAgent(wantAgentInfo, (err: BusinessError, data: WantAgent) => {
      if (err) {
        console.error(`Failed to get want agent. Code is ${err.code}, message is ${err.message}`);
        return;
      }
      console.info('Succeeded in getting want agent.');
      let notificationRequest: notificationManager.NotificationRequest = {
        id: 1,
        content: {
          notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
          normal: {
            title: params.title,
            text: params.content,
          },
        },
        notificationSlotType: notificationManager.SlotType.SOCIAL_COMMUNICATION,
        wantAgent: data,
      };

      notificationManager.publish(notificationRequest, (err: BusinessError) => {
        if (err) {
          console.error(`Failed to publish notification. Code is ${err.code}, message is ${err.message}`);
          return;
        }
        console.info('Succeeded in publishing notification.');
      });
    });
  }
}



相关文章

  • Netty 实现长连接消息推送初尝试

    由于我最近在研究推送功能,计划在项目中接入5大厂家推送服务,然后有部分厂家推送服务只提供通知栏推送功能,并不提供自...

  • Android 推送点击跳转与华为推送神坑

    实现Android推送功能,选择了接入华为推送和小米推送,结果步入了华为推送的一个神坑?,需求其实很简单,就是服务...

  • 集成个推推送

    背景很多时候,我们的APP需要接入接收推送的功能,市面上有许多提供推送服务的SDK,比如小米推送、极光推送、个推推...

  • 微信小程序消息推送 2019-04-19

    消息推送 接入微信小程序消息推送服务,开发者需要按照如下步骤完成: 1.填写服务器配置 2.验证服务器地址的有效性...

  • 其他拉活方式

    推送拉活:根据终端不同,在小米手机(包括 MIUI)接入小米推送、华为手机接入华为推送。 Native拉活:通过N...

  • 原创一个IM即时消息系统架构设计

    组成http网关:认证、负载均衡网络接入层:维持长连接,接收、推送消息业务服务层:聊天业务相关的消息处理服务red...

  • flutter接入推送功能,包含IOS端APNs推送,Andro

    原文地址 最近公司的APP需要接入推送功能,市面上挑选、对比了很多推送服务商,最终Android端选定了腾讯的移动...

  • 集成、配置就是这么简单

    快速的接入集成推送SDK,快速实现小米,华为,魅族,OPPO的推送接入: http://open.res.flym...

  • 小米消息推送服务接入流程

    考虑到接下来的一份工作可能会从事消息推送服务的开发,于是为了能够更快的熟悉业务,花了点时间研究小米的消息推送服务的...

  • 极光推送的几个问题

    极光推送的几个问题 最近接入极光推送遇到了几个问题 服务端发出通知没有声音 需要设置声音字段的值, sound:'...

网友评论

      本文标题:鸿蒙+next+接入推送服务

      本文链接:https://www.haomeiwen.com/subject/efnmdjtx.html