代码:
const auth = require('./utils/auth.js'); // 引入 auth.js
// app.js
App({
onLaunch() {
// 原有登录检查逻辑
const isLoggedIn = auth.checkLogin();
if (!isLoggedIn) {
wx.removeStorageSync('token');
wx.removeStorageSync('userInfo');
wx.reLaunch({ url: '/pages/login/login' });
}
// 新增定时定位逻辑
this.startLocationInterval();
},
startLocationInterval() {
// 立即执行一次
this.getAndCacheLocation();
// 设置30秒定时器
this.locationTimer = setInterval(() => {
this.getAndCacheLocation();
}, 30000);
},
getAndCacheLocation() {
wx.getLocation({
type: 'wgs84',
success: (res) => {
console.log("lat="+res.latitude+'&lon='+res.longitude)
wx.setStorageSync('lastLocation', {
latitude: res.latitude,
longitude: res.longitude,
timestamp: new Date().getTime()
});
},
fail: (err) => {
console.error('定位失败', err);
}
});
},
onHide() {
// 小程序进入后台时清除定时器
if (this.locationTimer) {
clearInterval(this.locationTimer);
}
},
onUnload() {
// 双重保险
if (this.locationTimer) {
clearInterval(this.locationTimer);
this.locationTimer = null;
}
},
onShow() {
// 小程序回到前台时重启定时器
this.startLocationInterval();
}
})
最后注意清除定时器:
