uni-push.uvue 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. <template>
  2. <!-- #ifdef APP -->
  3. <scroll-view style="flex: 1">
  4. <!-- #endif -->
  5. <view>
  6. <!-- #ifdef APP-ANDROID -->
  7. <button class="normal-button" type="default" @click="handleCreateChannel(true)">
  8. 创建通知渠道 | setPushChannel
  9. </button>
  10. <button class="normal-button" type="default" @click="handleGetAllChannels">
  11. 获取所有通知渠道信息 | getAllChannels
  12. </button>
  13. <textarea style="width: 100%;" :disabled="true" :value="channelInfo"></textarea>
  14. <!-- #endif -->
  15. <!-- #ifdef APP -->
  16. <button class="normal-button" type="default" @click="handleCreateLocalNotification">
  17. 创建本地通知消息 | createPushMessage
  18. </button>
  19. <text class="instructions">
  20. 不同手机厂商的角标显示规则不同,有部分设备的rom版本不支持显示角标,另有部分rom需要在应用的通知管理里开启`桌面角标`配置,才可以设置角标成功。\n
  21. 部分rom需要在设置中同时开启`通知开关`和`桌面角标`配置,才允许设置角标,例如鸿蒙4.2。 \n
  22. 另外针对高版本小米设备,会借助创建通知栏消息来设置角标数,所以设置时需要注意是否有权限创建通知栏消息。
  23. </text>
  24. <button class="normal-button" type="default" @click="handleSetBadge">
  25. 设置角标为5 | setAppBadgeNumber(5)
  26. </button>
  27. <button class="normal-button" type="default" @click="handleCleanBadge">
  28. 清空角标 | setAppBadgeNumber(0)
  29. </button>
  30. <!-- #endif -->
  31. <button class="normal-button" type="default" @click="handleSendPushMessage">
  32. 发送通知消息 | sendPushMessage
  33. </button>
  34. <button class="normal-button uni-common-mb" type="default" @click="handleGetClientId">
  35. 获取cid | getPushClientId
  36. </button>
  37. <button class="normal-button" type="default" @click="handleOnPushMessage">
  38. 注册回调 | onPushMessage
  39. </button>
  40. <button class="normal-button" type="default" @click="handleOffPushMessage">
  41. 注销回调 | offPushMessage
  42. </button>
  43. </view>
  44. <!-- #ifdef APP -->
  45. </scroll-view>
  46. <!-- #endif -->
  47. </template>
  48. <script setup>
  49. // 自动化测试
  50. type TypeJestResult = {
  51. clientId : string,
  52. sendPushMessageRes : number,
  53. onPushMessageType:string,
  54. onPushMessageCallbackInfo:string
  55. }
  56. type TypeIsRegister = {
  57. state:boolean
  58. }
  59. const jestResult = reactive({
  60. clientId:"",
  61. sendPushMessageRes:-1,
  62. onPushMessageType:"",
  63. onPushMessageCallbackInfo:""
  64. } as TypeJestResult)
  65. // 自动化测试
  66. const autoTest = ref(false);
  67. const updateAutoTest = (value : boolean) => {
  68. autoTest.value = value
  69. }
  70. const channelInfo = ref("")
  71. const onPushMessageCallback = (res : OnPushMessageCallbackResult) => {
  72. // 自动化测试
  73. jestResult.onPushMessageType = res.type
  74. jestResult.onPushMessageCallbackInfo = JSON.stringify(res.data)
  75. if (!autoTest.value) {
  76. uni.showModal({
  77. title: "onPushMessage回调信息",
  78. content: `type:${res.type} \n data:${JSON.stringify(res.data)}`
  79. })
  80. }
  81. }
  82. // 为兼容Android测试例中能获取到,此处用reactive定义
  83. const isRegister = reactive({
  84. state:false
  85. } as TypeIsRegister);
  86. const handleOnPushMessage = () => {
  87. if (isRegister.state) {
  88. uni.showToast({
  89. icon: "error",
  90. title: "无需重复注册"
  91. })
  92. return
  93. }
  94. uni.onPushMessage(onPushMessageCallback)
  95. isRegister.state = true
  96. uni.showToast({
  97. title: "成功注册"
  98. })
  99. }
  100. const handleOffPushMessage = () => {
  101. if (!isRegister.state) {
  102. uni.showToast({
  103. icon: "error",
  104. title: "未注册, 无需注销"
  105. })
  106. return
  107. }
  108. uni.offPushMessage(onPushMessageCallback)
  109. isRegister.state = false
  110. uni.showToast({
  111. title: "成功注销"
  112. })
  113. }
  114. const handleCreateChannel = (showToast : boolean) => {
  115. // #ifdef APP-ANDROID
  116. const manager = uni.getPushChannelManager()
  117. manager.setPushChannel({
  118. channelId: "msg-pass",
  119. channelDesc: "留言审核通过",
  120. soundName: "#填写配置的声音文件名#",
  121. enableLights: true,
  122. enableVibration: true,
  123. importance: 4,
  124. lockscreenVisibility: 1
  125. } as SetPushChannelOptions)
  126. if (showToast) {
  127. uni.showToast({
  128. title: "设置渠道成功"
  129. })
  130. }
  131. // #endif
  132. }
  133. const handleGetAllChannels = () => {
  134. // #ifdef APP-ANDROID
  135. const manager = uni.getPushChannelManager()
  136. console.log("channels : " + manager.getAllChannels());
  137. channelInfo.value = `渠道信息为: \n ${manager.getAllChannels()}`
  138. // #endif
  139. }
  140. const handleCreateLocalNotification = () => {
  141. if (uni.getAppAuthorizeSetting().notificationAuthorized == "authorized") {
  142. handleCreateChannel(false)
  143. const date = new Date();
  144. const hour = date.getHours()
  145. const minute = date.getMinutes()
  146. const second = date.getSeconds()
  147. const formateTime = (target : number) : string => {
  148. return target < 10 ? `0${target}` : `${target}`
  149. }
  150. uni.createPushMessage({
  151. title: "主标题(title)",
  152. content: `内容(content),创建时间: ${formateTime(hour)}:${formateTime(minute)}:${formateTime(second)}`,
  153. cover: false,
  154. channelId: "msg-pass",
  155. when: Date.now() + 10000,
  156. icon: "/static/uni.png",
  157. sound: "system",
  158. delay: 1,
  159. payload: {
  160. pkey: "pvalue1"
  161. },
  162. // #ifdef APP-HARMONY
  163. category: "SOCIAL_COMMUNICATION",
  164. // #endif
  165. // #ifndef APP-HARMONY
  166. category: "IM",
  167. // #endif
  168. success(res) {
  169. console.log("res: " + res);
  170. uni.hideToast()
  171. uni.showToast({
  172. title: "创建本地通知消息成功"
  173. })
  174. },
  175. fail(e) {
  176. console.log("fail :" + e);
  177. uni.hideToast()
  178. uni.showToast({
  179. title: "创建本地通知消息失败",
  180. icon: "error"
  181. })
  182. }
  183. })
  184. } else {
  185. uni.showToast({
  186. title: "请在设置中开启通知权限",
  187. icon: "error"
  188. })
  189. }
  190. }
  191. async function getPushClientId(): Promise<string>{
  192. let pushClientId = '';
  193. let res:void = await new Promise<void>(resolve => {
  194. uni.getPushClientId({
  195. success: (res: GetPushClientIdSuccess) => {
  196. console.log(res.cid)
  197. pushClientId = res.cid
  198. resolve()
  199. },
  200. fail: (err: GetPushClientIdFail) => {
  201. resolve()
  202. console.error(err);
  203. if (err.message.includes('uniPush is not enabled')) {
  204. uni.showModal({
  205. title: '获取cid失败',
  206. content: '当前项目未启用uni-push,检查manifest.json中的uni-push配置',
  207. showCancel: false
  208. });
  209. } else if (err.message.includes('getPushClientId:fail register fail: {\"errorCode\":1,\"errorMsg\":\"\"}')) {
  210. uni.showModal({
  211. title: '获取cid失败',
  212. content: '当前项目未开通uni-push,开通文档:https://uniapp.dcloud.net.cn/unipush-v2.html#%E7%AC%AC%E4%B8%80%E6%AD%A5-%E5%BC%80%E9%80%9A',
  213. showCancel: false
  214. });
  215. } else {
  216. uni.showToast({
  217. title: `获取cid失败`,
  218. icon: "error"
  219. })
  220. }
  221. }
  222. })
  223. })
  224. return pushClientId
  225. }
  226. const handleGetClientId = async():Promise<void> =>{
  227. uni.showLoading({
  228. title: "正在获取cid",
  229. })
  230. const cid = await getPushClientId()
  231. if (cid != '') {
  232. // 自动化测试
  233. jestResult.clientId = cid
  234. if (!autoTest.value) {
  235. uni.showModal({
  236. title: "获取cid",
  237. content: "获取cid成功" + cid,
  238. showCancel: false
  239. })
  240. }
  241. }
  242. uni.hideLoading()
  243. }
  244. const handleSendPushMessage = async():Promise<void>=> {
  245. const pushClientId = await getPushClientId()
  246. if (pushClientId == ''){
  247. return
  248. }
  249. const uniPushCo = uniCloud.importObject("uni-push-co")
  250. try {
  251. const res = await uniPushCo.sendPushMessage(pushClientId)
  252. // 自动化测试
  253. jestResult.sendPushMessageRes = res.errCode as number
  254. if (!autoTest.value) {
  255. uni.showToast({
  256. title: "发送通知消息成功"
  257. })
  258. }
  259. } catch (err:any) {
  260. const error = err as UniCloudError
  261. console.error(error)
  262. if (!autoTest.value) {
  263. uni.showToast({
  264. title: "发送通知消息失败",
  265. icon: "error"
  266. })
  267. }
  268. }
  269. }
  270. const handleSetBadge = () => {
  271. if (uni.getDeviceInfo().deviceBrand?.toLowerCase() == "xiaomi") {
  272. if (uni.getAppAuthorizeSetting().notificationAuthorized == "authorized") {
  273. uni.setAppBadgeNumber(5, {
  274. title: "AppName",
  275. content: "您有5条未读消息"
  276. } as BadgeOptions)
  277. uni.showToast({
  278. title: "设置应用角标数为5"
  279. })
  280. } else {
  281. uni.showToast({
  282. title: "请在设置中开启通知权限",
  283. icon: "error"
  284. })
  285. }
  286. } else {
  287. uni.setAppBadgeNumber(5)
  288. uni.showToast({
  289. title: "设置应用角标数为5"
  290. })
  291. }
  292. }
  293. const handleCleanBadge = () => {
  294. if (uni.getDeviceInfo().deviceBrand?.toLowerCase() == "xiaomi") {
  295. if (uni.getAppAuthorizeSetting().notificationAuthorized == "authorized") {
  296. uni.setAppBadgeNumber(0, {} as BadgeOptions)
  297. uni.showToast({
  298. title: "清空应用角标数"
  299. })
  300. } else {
  301. uni.showToast({
  302. title: "请在设置中开启通知权限",
  303. icon: "error"
  304. })
  305. }
  306. } else {
  307. uni.setAppBadgeNumber(0)
  308. uni.showToast({
  309. title: "清空应用角标数"
  310. })
  311. }
  312. }
  313. // 自动化测试
  314. defineExpose({
  315. jestResult,
  316. autoTest,
  317. updateAutoTest,
  318. isRegister,
  319. handleSendPushMessage,
  320. handleGetClientId,
  321. handleOnPushMessage,
  322. handleOffPushMessage
  323. })
  324. </script>
  325. <style>
  326. .normal-button {
  327. width: 100%;
  328. }
  329. .instructions {
  330. margin-top: 10px;
  331. margin-left: 10px;
  332. margin-right: 10px;
  333. background-color: #eee;
  334. }
  335. </style>