dcloud 5+ 监听安卓前后台切换状态 并后台运行程序
监听安卓前后台切换状态
function monitorRunStatus() {
// 部分型号监听“应用从前台切换到后台”和“应用从前台切换到后台”事件会重复调用2次,加个判断
var ispause = false;
document.addEventListener(
'pause',
() => {
if (!ispause) {
ispause = true;
// console.log('应用从前台切换到后台');
appShowIsChange(true);
}
},
false,
);
document.addEventListener(
'resume',
() => {
if (ispause) {
ispause = false;
// console.log('应用从后台切换到前台');
appShowIsChange(false);
}
},
false,
);
}
切换到后台时程序继续运行
function appShowIsChange(pageHide) {
if (window.plus) {
if (pageHide) {
var currentMainActivity = plus.android.runtimeMainActivity();
currentMainActivity.moveTaskToBack(false);
console.log('将当前应用程序退到后台');
} else {
var currentMainActivity = plus.android.runtimeMainActivity();
var systemActivityManager = currentMainActivity.getSystemService(currentMainActivity.ACTIVITY_SERVICE);
plus.android.importClass(systemActivityManager);
systemActivityManager.moveTaskToFront(currentMainActivity.getTaskId(), 0);
console.log('恢复程序运行');
}
} else {
document.addEventListener(
'plusready',
() => {
if (pageHide) {
var currentMainActivity = plus.android.runtimeMainActivity();
currentMainActivity.moveTaskToBack(false);
// console.log('将当前应用程序退到后台');
} else {
var currentMainActivity = plus.android.runtimeMainActivity();
var systemActivityManager = currentMainActivity.getSystemService(currentMainActivity.ACTIVITY_SERVICE);
plus.android.importClass(systemActivityManager);
systemActivityManager.moveTaskToFront(currentMainActivity.getTaskId(), 0);
// console.log('恢复程序运行');
}
},
false,
);
}
}