APP接收后台推送提示消息并展示
1.开通消息推送,根据需求我们选择uniPush 2.0 进行消息推送
2.根据官网提示,我们需要在uniapp的云空间开发中心 网址:开发者中心 去配置,选择uni-push的2.0(支持全端推送)的应用信息去填写。填写过程发现,出来要配置包名和应用签名之外(之前以个人名义申请的安卓证书),还需要配置云服务空间,没有云服务空间将无法开通此服务。
3.开通云服务空间,根据uniapp官网提示,创建uniCloud云开发环境,关联云服务空间或项目,因为之前没有用过云服务,所以需要新建云服务空间,我们可以选择阿里云或者腾讯云,付费方式有三种,免费的话是只有一个月,一个账号只有一次,剩下两种就是包年包月和按量计费(跟买服务器差不多),大概需要多少钱可以看下边两张图。
4.开通服务空间之后才能在项目中去关联云服务空间,关联之后,因为我们的需求是实现app的离线推送,故我们需要去各个手机开发中心配置厂商设置,然后在这里一一配置才能实现消息推送。注册这些平台需要公司的信息才可以完成。
5.实现在线推送,创建云函数,写完之后点击上传并运行
'use strict';
const uniPush = uniCloud.getPushManager({
appId: "__UNI__FE0EA1A"
})
exports.main = async (event) => {
console.log("入参", event);
let obj = event.body ? JSON.parse(event.body) : {};
const res = await uniPush.sendMessage({
"push_clientid": event.cids, // 设备id,支持多个以数组的形式指定多个设备,如["cid-1","cid-2"],数组长度不大于1000
"title": event.title, // 标题
"content": event.content, // 内容
"payload": event.data, // 数据
"force_notification": true, // 服务端推送 需要加这一句
"request_id": event.request_id, //请求唯一标识号,10-32位之间;如果request_id重复,会导致消息丢失
"options": event.options, //消息分类,没申请可以不传这个参数
})
};
6. 在App.vue页面编写拿到客户端推送标识,传递要传的参数,最后调用云函数。
onLaunch: function() {
this.initApp()
console.log('App Launch')
// #ifdef APP-PLUS
uni.getPushClientId({
success: (res) => {
let push_clientid = res.cid
console.log('客户端推送标识:', push_clientid);
function getId() {
let yy = new Date().getFullYear();
let mm = new Date().getMonth() + 1;
let dd = new Date().getDate();
let hh = new Date().getHours();
let mf = new Date().getMinutes() < 10 ? "0" + new Date().getMinutes() : new Date()
.getMinutes();
let ss = new Date().getSeconds() < 10 ? "0" + new Date().getSeconds() : new Date()
.getSeconds();
let Randnum = "";
for (var i = 0; i < 10; i++) {
Randnum += Math.floor(Math.random() * 10);
}
return "ID_" + yy + mm + dd + hh + mf + ss + Randnum;
}
const request_id = getId();
// 定义需要传递给云函数的参数
const params = {
alias: "测试",
cids: push_clientid,
title: "2111111111111111114",
content: "4444444444444444 ",
data:"2222222222222222222",
request_id: request_id
};
const functionName = 'test';
uniCloud.callFunction({
name: functionName,
data: params,
success: (res) => {
console.log('云函数调用成功', res);
},
fail: (err) => {
console.error('云函数调用失败', err);
}
})
},
fail(err) {
console.log(err)
}
})
// #endif
// 调用云函数
},