手机系统
- 安卓_华为:切后台会保留定时器,但是切回来会触发2个定时器一起轮训
- IOS_苹果6:切后台立马挂起不再触发定时器,切回来回复定时器
实现思路
障眼法:
原理:监听进入后台时存时间戳,停掉定时器,再进入前台时计算时间差,如果剩余时间大于时间差,则减去时间差,否则复制剩余时间为0;
直接法:
Apple只允许三种情况下App在后台一直执行,音频视频、定位、未知(还有一种没查到),如果是直播、视频播放、地图类的应用可以这样做,但是有些小需求则无需这样;
封装倒计时方法
// 倒计时
startTime(startTime, curTime, duration) { // 开始计时
if (this.durationTimer) clearInterval(this.durationTimer);
let entTime = duration * 60 * 1000 - (curTime - startTime); // 剩余时间
this.durationTimer = setInterval(() => {
if (entTime < 1000) {
clearInterval(this.durationTimer);
this.advanceSubmit(1);
return;
};
entTime = entTime - 1000;
let th = Math.floor(entTime / (1000 * 60 * 60) % 24);
let tm = Math.floor(entTime / (1000 * 60) % 60);
let ts = Math.floor(entTime / 1000 % 60);
this.countDown = `${th < 10 ? '0' + th : th}:${tm < 10 ? '0' + tm : tm}:${ts < 10 ? '0' + ts : ts}`;
}, 1000);
},
监听手机切后台
addMonitorProgram() { // 添加监听前台后台
const pauseFun = () => {
if (this.backgroundOperation.state === 0) return;
this.backgroundOperation.state = 0;
this.handleHeception();
};
const resumeFun = () => {
if (this.backgroundOperation.state === 1) return;
this.backgroundOperation.state = 1;
this.handleBackstage();
};
document.addEventListener('pause', pauseFun, false); // 从前台切换到后台
document.addEventListener('resume', resumeFun, false); // 从后台切换到前台
this.backgroundOperation.pause = pauseFun;
this.backgroundOperation.resume = resumeFun;
},
removeMonitorProgram() { // 移除监听
if (this.backgroundOperation.pause) {
document.removeEventListener('pause', this.backgroundOperation.pause, false);
}
if (this.backgroundOperation.resume) {
document.removeEventListener('resume', this.backgroundOperation.resume, false);
}
},