1. Push服务介绍华为Push是华为HMS开放能力中的一项消息推送功能,它提供了从服务器到终端的消息推送平台和通道。应用服务器可以通过华为Push,将最新的消息发送到手机上,即使在应用未启动的情况下,用户也可以在手机通知栏中收到Push消息。 使用场景 使用要求 l 使用华为快应用加载器开发测试。 l EMUI8.0及以上版本的华为手机; Push消息类型 2. 开发实现开发流程总体流程如下图所示: 开发者访问AGC网站进行帐号注册及实名认证,接着创建快应用,打开Push服务开关,配置Push回执(可选),接下来快应用客户端开发、API调用,并将regID上报到开发者服务器,开发者服务端进入开发流程,接收客户端的数据并实现服务端接口发送Push消息。当客户端和服务端开发完毕,测试您的Push能力,测试通过后提交您的快应用,审核上架发布。 2.1 获取regID
调用push.getProvider 接口判断是否支持Push能力,如果支持,调用push.subscribe 接口获取设备标识regID。然后和本地数据库缓存的regID进行对比,如果不相等,更新本地数据库的值,并将regID上报到开发者服务器上。regId一般情况下不会发生变化,所以不需要每次获取后都上报到服务器。开发者服务器收到更新后的regID,也需要替换更新。 我们推荐在快应用app.ux文件中实现获取regID。 app.ux
<script>
import push from '@service.push';
import fetch from '@system.fetch';
import prompt from '@system.prompt';
const injectRef = Object.getPrototypeOf(global) || global;
// 注入regeneratorRuntime
injectRef.regeneratorRuntime = require('@babel/runtime/regenerator');
module.exports = {
dataApp: {
pushtoken: ''
},
onCreate() {
console.info('Application onCreate');
setTimeout(() => {
this.checkPushIsSupported();
}, 1000);
},
checkPushIsSupported() {
let provider = push.getProvider();
console.log("checkPush provider= " + provider);
if (provider === 'huawei') {
this.pushsubscribe();
}
},
pushsubscribe() {
console.log("pushsubscribe start");
var that = this;
push.subscribe({
success: function (data) {
console.log("push.subscribe succeeded, result data=" + JSON.stringify(data));
that.dataApp.pushtoken = data.regId;
console.log("app oncreate this.dataApp.pushtoken=" + that.dataApp.pushtoken);
that.checkToken();
},
fail: function (data, code) {
console.log("push.subscribe failed, result data=" + JSON.stringify(data) + ", code=" + code);
},
complete: function () {
console.log("push.subscribe completed");
}
})
},
checkToken() {
var subscribeToken = this.dataApp.pushtoken;
console.log("checkToken subscribeToken= " + subscribeToken);
var storage = require("@system.storage");
var that = this;
storage.get({
key: 'token',
success: function (data) {
console.log("checkToken storage data= " + data);
if (subscribeToken !== data) {
//upload it to your own service server
that.uploadToken(subscribeToken);
that.saveToken(subscribeToken);
} else {
console.log("checkToken regid is the same as local storage");
}
},
fail: function (data, code) {
console.log("checkToken handling fail, code = " + code);
}
})
},
saveToken(subscribeToken) {
console.log("saveToken");
var storage = require("@system.storage");
storage.set({
key: 'token',
value: subscribeToken,
success: function (data) {
console.log("saveToken handling success");
},
fail: function (data, code) {
console.log("saveToken handling fail, code = " + code);
}
})
},
uploadToken(subscribeToken) {
console.log("uploadToken");
var that = this;
var body = {
xx: subscribeToken
};
fetch.fetch({
url: 'https://xxx',
method: 'POST',
data: body,
success: function (data) {
console.log("uploadToken code: " + data.code);
console.log("uploadToken data: " + data.data);
},
fail: function (data, code) {
console.log("handling fail, code = " + code);
}
})
},
pushunsubscribe() {
push.unsubscribe({
success: function (data) {
console.log('push.unsubscribe succeeded, result data = ' + JSON.stringify(data));
prompt.showToast({
message: 'push.unsubscribe succeeded',
duration: 2000,
gravity: 'center'
})
},
fail: function (data, code) {
console.log('push.unsubscribe failed, result data = ' + JSON.stringify(data) + ', code = ' + code);
},
complete: function () {
console.log('push.unsubscribe completed');
}
})
}
}
</script>
2.2发送通知栏Push消息AGC页面上发送通知栏消息首先要登录AGC网站,点击我的项目,选择对应的快应用卡片,点击左侧导航栏增长->推送服务, 点击右上角“添加推送通知”按钮,输入消息名称、消息摘要、消息内容等。“点击通知动作”只支持“打开应用”,不支持“打开网页”。App页面选择“首页”,快应用不支持“通知按钮”。选择你要推送的目标快应用,推送范围选择指定设备,指定设备中输入客户端获取到的regID,因为是给加载器中的快应用推送,需要勾选“发送到快应用调试器”。 客户端fetch接口模拟服务器发送本demo是使用客户端fetch接口模拟开发者服务器发送。服务器接口发送涉及到两个post请求,一个是获取accessToken接口,成功获得accessToken后,将值传递给另一个post请求“发送透传消息”的参数中。 客户端界面有两个按钮,分别模拟“发送通知栏消息”和“取消订阅消息”。sendNotifyMsg方法中实现了发送通知栏消息的功能。 sendnotify.ux
<template>
<div class="doc-page">
<input type="button" class="btn" value="send notify msg" onclick="sendNotifyMsg" />
<input type="button" class="btn" value="Do not receive Push messages" onclick="unregister" />
</div>
</template>
<style>
.doc-page {
flex-direction: column;
flex-direction: column;
justify-content: center;
align-content: center;
align-items: center;
}
.btn {
border-radius: 8px;
margin-top: 16px;
width: 80%;
background-color: #4169e1;
color: white;
}
.btn:active {
background-color: #20b2aa;
}
</style>
<script>
import router from "@system.router"
import prompt from '@system.prompt'
import push from '@service.push';
import fetch from '@system.fetch';
import account from '@service.account';
export default {
props: ['websrc'],
data: {
attoken: '',
},
onInit: function () {
//this.$page.setTitleBar({text: 'Simulating Notify Message Sending'});
this.$page.setTitleBar({ text: 'Simulating Notify Message Sending', textColor: '#FFFFFF', backgroundOpacity: 0.9 });
},
sendNotifyMsg: async function () {
try {
var body = {
grant_type: 'client_credentials',
client_id: '101266687',
client_secret: 'd873aa90c3e8792517317e09f24b97df366ee10433b2f1bb3282d6ca6ce3f425'
}
const response = await fetch.fetch({
url: 'https://login.cloud.huawei.com/oauth2/v2/token',
method: 'POST',
data: body
})
var result = response.data.data;
console.info('getAccessTokenV3 sucess data : ', result)
this.attoken = JSON.parse(result).access_token;
console.info('getAccessTokenV3 sucess attoken: ', this.attoken)
this.beginSendNotifyMsg();
} catch (err) {
console.info('getAccessTokenV3 fail code: ', err.code)
console.info('getAccessTokenV3 fail data: ', err.data)
}
},
beginSendNotifyMsg: async function () {
console.log("begin send push msg V3");
var token = this.$app.$def.dataApp.pushtoken;
console.log("send push msg app token=" + token);
let tokenlist = Array.of(token);
console.log("send push msg tokeb list=" + tokenlist);
var mData = {
"pushtype": 0,
"pushbody": {
"title": "How can young people make a living?",
"description": "Why did he choose to be a security guard after college graduation?",
"page": "/",
"params": {
"key1": "test1",
"key2": "test2"
},
"ringtone": {
"vibration": "true", //This field has been deprecated. The setting will not take effect.
"breathLight": "true" //This field has been deprecated. The setting will not take effect.
}
}
};
var formatJsonString = JSON.stringify(mData);
var messbody = {
"validate_only": false,
"message": {
"data": formatJsonString,
"android": {
"fast_app_target": 1
},
"token": tokenlist,
}
};
var access = 'Bearer ' + this.attoken;
try {
const response = await fetch.fetch({
url: 'https://push-api.cloud.huawei.com/v1/101266687/messages:send',
header: { 'Authorization': access, 'Content-Type': 'application/json;charset=utf-8;' },
method: 'POST',
data: messbody
});
console.info('sendPushMsg3 sucess code: ', response.data.code)
console.info('sendPushMsg3 sucess data: ', response.data.data)
console.info('sendPushMsg3 sucess headers: ', JSON.stringify(response.data.headers))
} catch (error) {
console.info("beginSendNotifyMsg catch error: " + error);
}
},
unregister: function () {
this.$app.pushunsubscribe();
},
getTimeStap: function () {
const between = Date.now();
console.log(" getTimeStap between=" + between);
},
onShow: function () {
console.info(" onshow");
},
onHide: function () {
console.info(" onHide");
},
onDestroy: function () {
console.info("ondestroy");
},
}
</script> 2.3 开发自检l Push 测试需要使用华为手机和华为加载器。 请务必先调用 push.getProvider 接口判断当前设备是否支持华为PUSH服务。 l 服务器接口给加载器中的快应用发送Push消息时,fast_app_target字段需要设置为1,给已上架华为应用市场的快应用发送时, fast_app_target字段需要设置为2。 l agc上给加载器中的快应用发送Push消息时,记得要勾选“发送到快应用调试器”。 l 收到通知栏push消息的前提条件是:该快应用“在桌面有快捷方式” 或者“添加到收藏中” ,满足任何1个条件都可以。 l 发送通知栏消息时,即pushtype=0时,即使不需要携带参数,params参数也必须写入pushbody体中,如: "params":{ } l 给已上架的快应用发送Push消息时,要注意满足发送频率要求,如果超过规定次数,消息会被频控的,无法到达客户端。 l 如果手机安装了手机管家,请务必在“自启动”选项中,将快应用中心的开关打开。 更多FAQ和案例请参考华为快应用接入push服务官网: https://developer.huawei.com/consumer/cn/doc/development/quickApp-Guides/quickapp-access-push-kit-0000001126547701#section557916411554
|