rp_10012/assets/Loading/scripts/AntiSleepManager.ts

67 lines
1.8 KiB
TypeScript

import { _decorator, Component, Node } from 'cc';
import NoSleep from 'nosleep.js';
const { ccclass,property } = _decorator;
@ccclass('AntiSleepManager')
export class AntiSleepManager extends Component {
private noSleep: NoSleep | null = null;
private wakeLock: any = null;
_enabled: boolean = false;
@property(Node)
btn_start: Node = null
onLoad() {
this.noSleep = new NoSleep();
}
clickStart(){
if(this._enabled) return
this.enableWakeLock();
}
async enableWakeLock() {
this._enabled = true
try {
if ('wakeLock' in navigator) {
this.wakeLock = await (navigator as any).wakeLock.request('screen');
// console.log('✅ 屏幕常亮已启用 (Wake Lock API)');
// 处理页面切换时丢失锁
document.addEventListener('visibilitychange', async () => {
if (document.visibilityState === 'visible') {
this.wakeLock = await (navigator as any).wakeLock.request('screen');
}
});
} else {
this.noSleep?.enable();
// console.log('✅ 屏幕常亮已启用 (NoSleep.js)');
}
} catch (err) {
this._enabled = false
// console.error('❌ 启用屏幕常亮失败:', err);
}
}
disableWakeLock() {
if (this.wakeLock) {
this.wakeLock.release();
this.wakeLock = null;
// console.log('🔒 Wake Lock 已关闭');
}
if (this.noSleep) {
this.noSleep.disable();
// console.log('🔒 NoSleep 已关闭');
}
}
onDestroy() {
// this.disableWakeLock();
}
}