How does Uni-App implement the message push function?

Original text link: How does Uni-App implement the message push function?

foreword

Here we use UniPush1.0 (a push service) that comes with uni-app , so we only introduce the implementation steps for UniPush1.0 .

Suggested articles:

Of course, UniPush2.0 has been released now (supported by HBuilderX 3.5.1 and above), and it is recommended to use UniPush2.0 for new projects .

If you want to use UniPush2.0 , please move to UniPush 2.0 User Guide .

Effect preview

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

insert image description here
insert image description here
The first five pictures are Android (HUAWEI P30 Pro) real machine effects, and the last three pictures are Ios (iPhone XS Max) real machine effects.

overview

product description

UniPush is an integrated unified push service launched by DCloud and Getui. It has built-in system-level push and third-party push such as Apple, Huawei, Xiaomi, OPPO, VIVO, Meizu, Google FCM and other mobile phone manufacturers .

Domestic Android 's Push is a chaotic world, because Google 's Push service FCM is blocked (starting from HBuilderX2.7.10 , Google FCM is supported, reference: https://ask.dcloud.net.cn/article/37356 ), so some Domestic Android mobile phone manufacturers have made their own push, such as Huawei, Xiaomi, OPPO, VIVO, Meizu, etc., but there are still many domestic mobile phone manufacturers that have not provided official push solutions. A three-party independent company, such as a push, provides an independent push solution.

Before UniPush , if only three-party push was used , many domestic mobile phones would not be able to keep the push process alive due to power-saving settings, resulting in push failure.

And if the official Push SDK of each Android phone is integrated and developed, with so many platforms, the workload will be huge, and the management and maintenance will be very troublesome.

UniPush solves this problem, developers only need to develop once. The system will automatically select the most reliable push channel on different mobile phones to send push messages to ensure the delivery rate.

UniPush not only reduces the development cost, but also improves the delivery rate of push , and it is free. It is the best solution for push at present.

Technology Architecture

Glossary

noun explain
notification message After specifying the notification title and content, Getui SDK will automatically display the notification bar message in the system notification bar, and at the same time ring or vibrate to remind the user (ring and vibration are affected by the setting status of the mobile phone system).
Transparent message That is, a custom message, the message body format can be defined by the customer, such as plain text, json string, etc. The transparent message push only transmits data without any processing. After receiving the transparent message, the client needs to perform follow-up action processing, such as notification bar display, pop-up box, etc.
ClientId The external user ID in the Getui business layer is used to identify the identity of the client. It is obtained by the third-party client and saved to the third-party server. It is the unique identification number of the Getui SDK, referred to as CID.
Push online When the app is running in the foreground, it sends a message through a push channel.
Offline push When the app is in the background, the screen is locked, or the process is closed, it sends a message through the manufacturer's channel. If the android multi-vendor is not integrated and the ios push certificate is not configured, the model cannot use offline push.

For more explanations of nouns, please refer to: Explanation of nouns .

Message push process

Open UniPush push service

UniPush has internally packaged a push and mainstream manufacturer SDK, and related services must be activated before use: Click here to view how to activate the UniPush push service .

Open the DCloud Developer Center , and after logging in, you will enter the list of my applications . Click uniPush on the left menu , and then select 1.0 or 2.0 to enter the Uni Push information page. The upper left corner displays the current application to be operated. Click to switch applications. As shown below:

When users use the UniPush function for the first time, they need to synchronize their identity information with UniPush. Users who have passed the real-name authentication will directly synchronize the real-name authentication information to Getui. As shown below:

Users who have not submitted real-name authentication information need to enter relevant information on the page and submit it, as shown in the following figure:

When an application activates the UniPush function, it needs to submit application-related information, as shown in the following figure:

insert image description here

Note: When applying for activation of UniPush , you need to ensure that the input Android package name or iOS Bundle ID must be consistent with the one configured during packaging, otherwise the push message may not be received.

Android platform:
The Android package name must be consistent with the Android package name configured when the App cloud is packaged in HBuilderX ; the Android application signature must be filled in with the SHA1 fingerprint of the certificate used for packaging . iOS platform: iOS BundleId must be consistent with **Bundle ID (AppID)** configured when App cloud packaging in HBuilderX .

If you have already opened UniPush , you will see the following page:

insert image description here

If you need to support mainstream Android vendors to receive offline push notifications, you need to complete: Android multi-vendor configuration .

The iOS platform also needs to upload the push certificate on the [Configuration Management] - [Application Configuration] page. For how to obtain the push certificate, please refer to Getui official document tutorial: iOS certificate configuration guide .

core code

unipush.js

// 监听push消息 以及 后台数据回复
import phoneInfo from '@/common/js/phone-info.js';
import store from '@/store'
let timer = null;
let numloop = 0;
import {
    
    
  pushEscalation // 绑定别名的接口
} from "@/api/client-notice.js"

// 消息推送 应用配置(这些给后端用的)
const uniPushObj = {
    
    
  cid: "",
  AppID: "你的AppID",
  AppKey: "你的AppKey",
  AppSecret: "你的AppSecret",
  MasterSecret: "你的MasterSecret",
}

export default {
    
    
  getInfo() {
    
    
    uni.getSystemInfo({
    
    
      success: res => {
    
    
        phoneInfo.systemInfo = res;
      }
    });
  },
  // 开启监听推送 
pushListener() {
    
    
  const token = uni.getStorageSync("token") || store.state.token;
  const platform = phoneInfo.systemInfo.platform.toLowerCase();
  // 点击推送信息
  plus.push.addEventListener('click', res => {
    
    
    // 其实在这里就可以根据你自己的业务去写了
    if (token) {
    
    
      if (platform == 'android') {
    
    
        const msg_type = res.payload.msg_type // 0 在线 || 1 离线
        // 做些什么 这里处理你的逻辑
        if (msg_type == 0) {
    
    
          console.log('安卓------在线');
        } else {
    
    
          console.log('安卓------离线');
        }
      } else {
    
    
        //  在线
        if (res.aps == null) {
    
    
          console.log('苹果------在线');
        } else {
    
    
        // 离线
          console.log('苹果------离线');
        }
      }
    } else {
    
    
      // 这里跳登录页了
      uni.redirectTo({
    
    
        url: `pages/Login-Reg/Login/email-login`
      })
    }
  });
  // 接收推送信息  在线
  plus.push.addEventListener('receive', res => {
    
    
    const messageTitle = res.title;
    const messageContent = res.content;
    if (platform == 'android') {
    
    
      /***  
        安卓监听不到  因为安卓这个格式被封装了,做成了通知栏展示
        换个格式就行(比如里面多个字段,或换个字段名)
      */
      /***
        此格式的透传消息由 unipush 做了特殊处理, 会自动展示通知栏 
        开发者也可自定义其它格式, 在客户端自己处理
      */
      //   "push_message": {
    
    
      //     "transmission": "{
    
    
      //       title:\"标题\",
      //       content:\"内容\",
      //       payload:\"自定义数据\"
      //     }"
      //   },
      // Hbulidx 版本大于 ## 3.4.18,安卓不再通知栏展示, 需要自行创建通知
      plus.push.createMessage(messageContent, res.payload, {
    
    
        title: messageTitle
      });
      // 或者在 onlaunch 写入
      // plus.push.setAutoNotification(true);
    } else {
    
    
      const type = res.type
      //【APP离线】收到消息,但没有提醒(发生在一次收到多个离线消息时,只有一个有提醒,但其他的没有提醒)  
      //【APP在线】收到消息,不会触发系统消息,需要创建本地消息,但不能重复创建
	    // 必须加msg.type验证去除死循环        
      if (res.aps == null && type == "receive") {
    
    
        //创建本地消息,发送的本地消息也会被receive方法接收到,但没有type属性,且aps是null  
        plus.push.createMessage(messageContent, res.payload, {
    
    
          title: messageTitle
        });
      }
    }
  });
  },
  // 循环获取clientid信息,直到获取到为止
  getClientInfoLoop() {
    
    
    plus.push.getClientInfoAsync(info => {
    
    
      // 如果info不存在,或者info存在,cid不存在则再次获取cid
      if (!info || !info.clientid) {
    
    
        console.log("cid为空=========================================");
        let infoTimer = null;
        infoTimer = setInterval(function() {
    
    
          if (cid) {
    
    
            clearInterval(infoTimer); //清定时器
            uni.showModal({
    
    
              content: cid
            })
            uni.setStorageSync('cid', cid); 
            uniPushObj.cid = cid 
          }
        }, 50);
      } else if (info && info.clientid) {
    
    
        let cid = info.clientid;
        uni.setStorageSync('cid', cid);
        uniPushObj.cid = cid
      }
    }, function(e) {
    
    
      console.log('Failed', JSON.stringify(e));
      let pinf = plus.push.getClientInfo();
      let cid = pinf.clientid; //客户端标识 
      if (cid) {
    
    
        uni.setStorageSync('cid', cid);
        uniPushObj.cid = cid
      }
    })
  },
  /** 
   * 向后台传送cid,绑定别名
   */
  passCid() {
    
    
    pushEscalation({
    
    
      "appid": uniPushObj.AppID,
      "cid": uniPushObj.cid
    }).then(response => {
    
    
      if (response.Code == 0) {
    
    
        console.log('----------> cid 绑定别名成功', response);
      }
    })
  },
}

phone-info.js

export default {
    
    
	systemInfo: {
    
    }, // 系统设备信息
	manifestInfo: "" || uni.getStorageSync("widgetInfo"), // manifest.json 应用信息
}

APP.view

<script>
  import phoneInfo from '@/common/js/phone-info.js';
  import uniPushListener from '@/common/js/unipush.js';
  export default {
      
      
    onLaunch: function() {
      
      
      uniPushListener.getInfo();
      // #ifdef APP-PLUS
      plus.screen.lockOrientation('portrait-primary'); //锁定屏幕方向
      uni.setStorageSync('cancelUpdate', 'false'); // 进来APP 重置更新弹窗
      // 获取App 当前版本号
      if (Object.keys(uni.getStorageSync('widgetInfo')).length == 0) {
      
      
          plus.runtime.getProperty(plus.runtime.appid, widgetInfo => {
      
      
              phoneInfo.manifestInfo = widgetInfo;
              uni.setStorageSync('widgetInfo', widgetInfo);
          });
      }
      uniPushListener.getClientInfoLoop(); // 循环获取cid
      plus.runtime.setBadgeNumber(0); // 角标清空
      uniPushListener.pushListener(); // 监听通知栏信息
      //#endif
    }
  };
</script>

Guess you like

Origin blog.csdn.net/qq_41356250/article/details/128845739