window.setWindowKeepScreenOn:设置屏幕是否为常亮状态。规范使用该接口:
解除屏幕常亮时会有try unlock日志输出。
加锁与解锁都只看type:0的。
通过try lock.*type: 0|try unlock.*type: 0过滤日志查看加锁解锁时间,如下所示,加锁和解锁之间时间间隔很短,设置屏幕常亮之后立即解除了屏幕常亮。
Client CreateRunningLock name: xxxxxx, type = 0 bundle name for vid=20020020, name=com.xxx.example CreateRunningLock name:kankan0_307088416, type:0, lockid:xxxxxxxx try Lock, name: xxxxxx_307088416, type: 0 lockid: xxxxxxxxx [UL_POWER] RUNNINGLOCK_SCREEN active, and the current power state is 0 runninglock message: LOCKID=xxxxxxxxxx PID=3304 UID=20020020 TYPE=0 try UnLock, name: xxxxxx_307088416, type: 0 lockid: xxxxxxxxxx
import common from '@ohos.app.ability.common';
import { BusinessError } from '@kit.BasicServicesKit';
import { window } from '@kit.ArkUI';
@Entry
@Component
struct S20250416165613637594 {
private controller: VideoController = new VideoController();
private innerResource: Resource = $rawfile('S20250416165613637594.mp4');
private windowClass?: window.Window = undefined;
aboutToAppear(): void {
(this.getUIContext().getHostContext() as common.UIAbilityContext).windowStage.getMainWindow().then((win) => {
this.windowClass = win;
}).catch((err: BusinessError) => {
console.error(`Failed to get the main window. Cause code: ${err.code}, message: ${err.message}`);
});
}
aboutToDisappear(): void {
this.setWindowKeepScreenOn(false);
}
build() {
Column() {
Video({
src: this.innerResource,
controller: this.controller
})
.margin({bottom: 20})
.autoPlay(true)
.objectFit(ImageFit.Contain)
.onStart(() => {
// 设置屏幕常亮
this.setWindowKeepScreenOn(true);
})
.onPause(() => {
// 关闭屏幕常亮
this.setWindowKeepScreenOn(false);
})
.onFinish(() => {
this.setWindowKeepScreenOn(false);
})
.onStop(() => {
this.setWindowKeepScreenOn(false);
})
}
.height('100%')
.width('100%')
.backgroundColor(Color.Black)
}
setWindowKeepScreenOn(isKeepScreenOn: boolean): void {
try {
this.windowClass?.setWindowKeepScreenOn(isKeepScreenOn, (err: BusinessError) => {
const errCode: number = err.code;
if (errCode) {
console.error(`Failed to set the screen to be always on. Cause code: ${err.code}, message: ${err.message}`);
return;
}
console.info('Succeeded in setting the screen to be always on.');
});
} catch (exception) {
console.error(`Failed to set the screen to be always on. Cause code: ${exception.code}, message: ${exception.message}`);
}
}
}