NoticeUtil.ets 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { common } from '@kit.AbilityKit';
  2. import { notificationManager } from '@kit.NotificationKit';
  3. import { BusinessError } from '@kit.BasicServicesKit';
  4. import { YTLog } from '../../../../Index';
  5. import { pushService } from '@kit.PushKit';
  6. import { userInfo } from '../models/UserInfo';
  7. class PushMessageUtil {
  8. private static instance: PushMessageUtil
  9. private isFirstRequestPermission: boolean = true
  10. private declare context: common.UIAbilityContext
  11. private readonly setDataPersistenceKey: string = 'setDataPersistenceKey'
  12. private constructor() {
  13. }
  14. static getInstance() {
  15. if (!PushMessageUtil.instance) {
  16. PushMessageUtil.instance = new PushMessageUtil()
  17. }
  18. return PushMessageUtil.instance
  19. }
  20. init(context: common.UIAbilityContext) {
  21. PersistentStorage.persistProp<boolean>(this.setDataPersistenceKey, this.isFirstRequestPermission)
  22. this.context = context
  23. this.isFirstRequestPermission = AppStorage.get<boolean>(this.setDataPersistenceKey) ?? true
  24. }
  25. //请求权限+推送token
  26. pushMessage(success: () => void) {
  27. notificationManager.isNotificationEnabled((err, enable) => {
  28. if (enable && !err) {
  29. //像后端推送pushToken
  30. this.pushToken(success)
  31. } else {
  32. if (this.isFirstRequestPermission) {
  33. notificationManager.requestEnableNotification(this.context)
  34. .then(() => {
  35. this.pushToken(success)
  36. })
  37. .catch((err: BusinessError) => {
  38. if (1600004 == err.code) {
  39. YTLog.error("requestEnableNotification refused" + err.code)
  40. } else {
  41. YTLog.error("requestEnableNotification failed:" + err.code + err.message)
  42. }
  43. })
  44. .finally(() => {
  45. this.isFirstRequestPermission = false
  46. })
  47. } else {
  48. notificationManager.openNotificationSettings(this.context)
  49. .then(() => {
  50. this.pushMessage(success)
  51. })
  52. .catch((err: BusinessError) => {
  53. if (1600004 == err.code) {
  54. YTLog.error("requestEnableNotification refused" + err.code)
  55. } else {
  56. YTLog.error("requestEnableNotification failed:" + err.code + err.message)
  57. }
  58. });
  59. }
  60. }
  61. })
  62. }
  63. private pushToken(success: () => void) {
  64. pushService.getToken((err, token) => {
  65. if (token && !err) {
  66. userInfo.setPushToken(token).pushPushTokenToBackEnd(success)
  67. } else {
  68. YTLog.error(err)
  69. }
  70. });
  71. }
  72. }
  73. export const pushMessageUtil = PushMessageUtil.getInstance()