二、项目首页代码 1、onLoad() {}cid处理 2、sendPushMessage() {}消息处理
三、推送结果 第一步参考上一篇(uniapp消息推送uni-push2.0(全局消息推送简易版))
uniapp消息推送(在线推送)uni-push2.0统一推送针对安卓(全局消息推送)①
一、创建云函数
在创建云函数文件index.js里面写入代码
'use strict';
const uniPush = uniCloud.getPushManager({
appId: "__UNI__FAF5116" //填写自己项目appid
})
exports.main = async (event)=>{
let obj = JSON.parse(event.body)
const res = await uniPush.sendMessage({
"push_clientid": obj.cids, // 设备id,支持多个以数组的形式指定多个设备,如["cid-1","cid-2"],数组长度不大于1000
"title": obj.title, // 标题
"content": obj.content, // 内容
"payload": obj.data, // 数据
"force_notification": true, // 服务端推送 需要加这一句
"request_id": obj.request_id //请求唯一标识号,10-32位之间;如果request_id重复,会导致消息丢失
})
return res //一定要return回去
};
二、项目首页代码
<template>
<view class="container">
<view class="">
<input type="text"style="border: 1rpx solid #cecece;margin-top: 50rpx;height: 80rpx;"placeholder="请输入标题" v-model="bt" />
<input type="text"style="border: 1rpx solid #cecece;margin: 50rpx 0rpx;height: 80rpx;"placeholder="内容" v-model="content"/>
</view>
<button @click="sendPushMessage">发送推送消息</button>
</view>
</template>
<script>
export default {
data(){
return{
deviceIds: [], // 存储设备 ID 的数组
bt: '',
content: ''
};
},
onLoad(){
// uni.hideLoading();
const that = this; // 保存 this 到变量 that
uni.getProvider({
service: 'push',
success: function(res){
if(res.provider.length >0){
uni.getPushClientId({
success: (res)=>{
console.log('设备 ID:', res.cid);
that.deviceIds.push(res.cid); // 使用保存的 that 来访问 deviceIds
},
fail: (err)=>{
console.error('获取设备 ID 失败:', err);
}
});
}
}
});
},
methods: {
sendPushMessage(){
uni.showLoading({
title:'正在推送...',
mask:true
})
// 准备要发送的数据
const dataToSend ={
cids: ["a5ee797bad57a32ae4efa374f26a9fcd"], // 使用存储的设备 CID(接收者cid)
title: this.bt,
content: this.content,
payload: {},
category: "",
request_id: "",
options: {}
};
console.log(dataToSend)
// 调用云函数,并将数据转换为 JSON 字符串
uniCloud.callFunction({
name: "cid_push", // 云函数名称
data: {
body: JSON.stringify(dataToSend) // 将数据转换为 JSON 字符串并赋值给 body
}
}).then(res =>{
console.log('云函数调用结果:', res);
}).catch(err =>{
console.error('云函数调用出错:', err);
});
},
}
};
</script>
<style scoped>
.container {
padding: 20px;
text-align: center;
}
button {
padding: 10px 20px;
background-color: #007aff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
.button-text {
color: #fff;
font-size: 12px;
}
</style>
1、onLoad() {}cid处理
uni.getProvider,uni.getPushClientId函数为了获取自己设备cid。实际项目中可进行保存在自己数据中。
2、sendPushMessage() {}消息处理
dataToSend 数据里面cids为消息接收者cid,此处为自己设备cid。实际项目中可通过接口查询消息接收者cid。
三、推送结果
© 版权声明
文章版权归原作者所有,本站只做转载和学习以及开发者个人原创。声明:下载本站资源即同意用户协议,本站程序仅供内部学习研究软件设计思想和原理使用,学习研究后请自觉删除,请勿传播,因未及时删除所造成的任何后果责任自负。
THE END
暂无评论内容