关于微信小程序:微信小程序热启动监听

有的业务须要监听热启动,比方,当再次关上小程序时,从新获取用户的实时定位

  1. 首先须要在app.js里写个自定义监听器,就叫watch好了,watch对象须要监听该页面data的变动,当data变动,就调用watch办法,代码如下:
  watch: function (watchBack) {
    let obj = this.globalData;
    Object.defineProperty(obj, "appShow", {
      configurable: true,
      enumerable: true,
      set: function (value) {
        watchBack(value);
      },
      get: function () {
        return this.appShow
      }
    })
  },

当然,要在app.js的对应办法里更新appShow

  onShow() {
    this.globalData.appShow = true
  },
  onHide() {
    this.globalData.appShow = false
  }
  1. 在须要更新定位的页面生命周期onLoad办法中调用该watch办法
    getApp().watch(this.watchBack)
    本页面的watchBack办法如下:

      watchBack(appShow) {
     if (appShow) {
       // 一旦热启动,就更新以后地位
       getUserLocationFunc().then(res => {
         this.setData({
           userLocation: res
         })
       })
     }
      }

    题外话:这里留神,小程序取得用户以后定位须要肯定的工夫,尽管很短暂,但同样是异步的,所以getUserLocationFunc办法返回promise对象,该办法是引入的公共办法

    const { getUserLocationFunc } = require('../../util/public.js')

    代码如下:

export const getUserLocationFunc = () => {
  return new Promise((resolve, reject) => {
    wx.getLocation({
      type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回间接给openLocation用的火星坐标,可传入'gcj02'
      success: async (response) => {
        // var speed = response.speed; // 速度,以米/每秒计
        // var accuracy = response.accuracy; // 地位精度
        let userLocation = {
          lng: response.longitude,
          lat: response.latitude
        }

        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            async success() {
              // 用户曾经批准小程序应用地位
              resolve(userLocation)
            }
          })
        } else {
          // 已受权,间接取得以后地位
          resolve(userLocation)
        }

      }
      
    })
  })
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理