WDPushNotificationManager.ets 4.09 KB

import { pushCommon, pushService } from '@kit.PushKit';
import { AAID } from '@kit.PushKit';
import { AccountManagerUtils, Logger, SPHelper, UserDataLocal } from 'wdKit/Index';
import { BusinessError } from '@kit.BasicServicesKit';
import notificationManager from '@ohos.notificationManager';
import { common, Want } from '@kit.AbilityKit';

const TAG = "NotificationManager"

/*
 * 远程推送通知管理类
 * Push Kit: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/push-introduction-0000001726287974
 * Notification Kit: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/notification-overview-0000001822162741
 * */
export class WDPushNotificationManager {

  private static instance: WDPushNotificationManager
  static getInstance() : WDPushNotificationManager {
    if (!WDPushNotificationManager.instance) {
      WDPushNotificationManager.instance = new WDPushNotificationManager()
    }
    return WDPushNotificationManager.instance
  }

  async requestEnableNotifications(context: common.UIAbilityContext) : Promise<boolean> {
    let enabled = await notificationManager.isNotificationEnabled()
    if (!enabled) {
      try {
        await notificationManager.requestEnableNotification(context)
        enabled = true
      } catch (err) {
        Logger.error(TAG, "请求通知权限报错: " + JSON.stringify(err))
        let error = err as BusinessError
        if (error.code == 1600004) {
          Logger.error(TAG, "请求通知权限 - 用户已拒绝")
        }
      }
    }
    Logger.info(TAG, "推送 enabled " + enabled)
    return enabled
  }

  async fetchTokenAndBindProfileId() {
    try {
      const pushToken: string = await pushService.getToken();
      Logger.info(TAG, "获取推送token: " + pushToken)

      //TODO: pushToken 上传至服务器
      SPHelper.default.save("devicePushToken", pushToken)

      if (AccountManagerUtils.isLoginSync()) {
        this.bindUserProfileId(UserDataLocal.getUserId())
      }

    } catch (err) {
      Logger.error(TAG, "获取推送token失败: " + JSON.stringify(err))
    }
  }

  // 禁止推送
  stopPush() {
    pushService.deleteToken()
  }

  /// 应用匿名标识符
  async getAAID() {
    let aaid: string = ""
    try {
      aaid = await AAID.getAAID();
      Logger.info(TAG, "获取应用匿名标识符AAID: " + aaid)
    } catch (err) {
      Logger.error(TAG, "获取应用匿名标识符AAID失败: " + JSON.stringify(err))
    }
    return aaid
  }

  // TODO: 登录时调用
  bindUserProfileId(profileId: string) {
    pushService.bindAppProfileId(pushCommon.AppProfileType.PROFILE_TYPE_APPLICATION_ACCOUNT, profileId).then(() => {
      Logger.info(TAG, "推送绑定profileId 成功: " + profileId)
    }).catch((err: BusinessError) => {
      Logger.error(TAG, "推送绑定profileId失败: " + profileId + " " + JSON.stringify(err))
    });
  }
  unbindUserProfileId(profileId: string) {
    pushService.unbindAppProfileId(profileId).then(() => {
      Logger.info(TAG, "推送解绑profileId 成功: " + profileId)
    }).catch((err: BusinessError) => {
      Logger.error(TAG, "推送解绑profileId失败: " + profileId + " " + JSON.stringify(err))
    });
  }

  sendLocalNotification() {
    let notificationRequest: notificationManager.NotificationRequest = {
      id: 1,
      content: {
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: "test_title",
          text: "test_text",
          additionalText: "test_additionalText"
        }
      }
    };
    notificationManager.publish(notificationRequest).then(() => {
      console.info("publish success");
    }).catch((err: BusinessError) => {
      console.error(`publish fail: ${JSON.stringify(err)}`);
    });
  }

  setBadgeNumber(number: number) : Promise<void> {
    return notificationManager.setBadgeNumber(number)
  }

  // 接收推送数据,包括启动和二次点击拉起
  // 参考:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/push-dev-0000001727885258
  onWant(want: Want) {
    Logger.info(TAG, "接收到推送?: " + JSON.stringify(want.parameters))
  }

}