| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- import { common } from '@kit.AbilityKit';
- import { notificationManager } from '@kit.NotificationKit';
- import { BusinessError } from '@kit.BasicServicesKit';
- import { YTLog } from '../../../../Index';
- import { pushService } from '@kit.PushKit';
- import { userInfo } from '../models/UserInfo';
- class PushMessageUtil {
- private static instance: PushMessageUtil
- private isFirstRequestPermission: boolean = true
- private declare context: common.UIAbilityContext
- private readonly setDataPersistenceKey: string = 'setDataPersistenceKey'
- private constructor() {
- }
- static getInstance() {
- if (!PushMessageUtil.instance) {
- PushMessageUtil.instance = new PushMessageUtil()
- }
- return PushMessageUtil.instance
- }
- init(context: common.UIAbilityContext) {
- PersistentStorage.persistProp<boolean>(this.setDataPersistenceKey, this.isFirstRequestPermission)
- this.context = context
- this.isFirstRequestPermission = AppStorage.get<boolean>(this.setDataPersistenceKey) ?? true
- }
- //请求权限+推送token
- pushMessage(success: () => void) {
- notificationManager.isNotificationEnabled((err, enable) => {
- if (enable && !err) {
- //像后端推送pushToken
- this.pushToken(success)
- } else {
- if (this.isFirstRequestPermission) {
- notificationManager.requestEnableNotification(this.context)
- .then(() => {
- this.pushToken(success)
- })
- .catch((err: BusinessError) => {
- if (1600004 == err.code) {
- YTLog.error("requestEnableNotification refused" + err.code)
- } else {
- YTLog.error("requestEnableNotification failed:" + err.code + err.message)
- }
- })
- .finally(() => {
- this.isFirstRequestPermission = false
- })
- } else {
- notificationManager.openNotificationSettings(this.context)
- .then(() => {
- this.pushMessage(success)
- })
- .catch((err: BusinessError) => {
- if (1600004 == err.code) {
- YTLog.error("requestEnableNotification refused" + err.code)
- } else {
- YTLog.error("requestEnableNotification failed:" + err.code + err.message)
- }
- });
- }
- }
- })
- }
- private pushToken(success: () => void) {
- pushService.getToken((err, token) => {
- if (token && !err) {
- userInfo.setPushToken(token).pushPushTokenToBackEnd(success)
- } else {
- YTLog.error(err)
- }
- });
- }
- }
- export const pushMessageUtil = PushMessageUtil.getInstance()
|