HarmonyOS 鸿蒙Next设备如何保持屏幕常亮?
HarmonyOS 鸿蒙Next设备如何保持屏幕常亮? 从系统设置和代码层面,是否都可以实现屏幕常亮?
开发者你好
1、当前使用系统设置,最长可设置10分钟的屏幕休眠时间 2、获取窗口实例对象后,调用setWindowKeepScreenOn方法可设置屏幕是否常亮。
let isKeepScreenOn: boolean = true;
let windowClass: window.Window = window.findWindow("test");
try {
windowClass.setWindowKeepScreenOn(isKeepScreenOn, (err: BusinessError) => {
const errCode: number = err.code;
if (errCode) {
console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err));
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: ' + JSON.stringify(exception));
}
仅在必要场景(导航、视频播放、绘画、游戏等场景)下,设置该属性为true;退出上述场景后,应当重置该属性为false;其他场景(无屏幕互动、音频播放等)下,不使用该接口;系统检测到非规范使用该接口时,可能会恢复自动灭屏功能。
更多关于HarmonyOS 鸿蒙Next设备如何保持屏幕常亮?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
代码上是有相关api的~
setWindowKeepScreenOn
setWindowKeepScreenOn(isKeepScreenOn: boolean, callback: AsyncCallback<void>): void
设置当前窗口位于前台时当前设备的屏幕是否为常亮状态,异源虚拟屏下不生效。使用callback异步回调。
仅在必要场景(导航、视频播放、绘画、游戏等场景)下,设置该属性为true;退出上述场景后,应当重置该属性为false;其他场景(无屏幕互动、音频播放等)下,不使用该接口;系统检测到非规范使用该接口时,可能会恢复自动灭屏功能。
系统能力: SystemCapability.WindowManager.WindowManager.Core
元服务API: 从API version 11开始,该接口支持在元服务中使用。
参数:
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| isKeepScreenOn | boolean | 是 | 设置屏幕是否为常亮状态。true表示常亮;false表示不常亮。 |
| callback | AsyncCallback<void> | 是 | 回调函数。 |
错误码:
| 错误码ID | 错误信息 |
|---|---|
| 401 | Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
| 1300002 | This window state is abnormal. |
| 1300003 | This window manager service works abnormally. |
import { BusinessError } from '@kit.BasicServicesKit';
let isKeepScreenOn: boolean = true;
try {
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}`);
}
在HarmonyOS Next中,通过@ohos.window的setKeepScreenOn(true)方法可使屏幕常亮。在UIAbility的onWindowStageCreate中获取windowStage.getMainWindow()后调用即可。或使用@ohos.app的keepScreenOn接口。
两种方式均可实现。简要概述如下:
-
系统设置层面:进入设备 设置 > 显示和亮度,找到 休眠 选项,选择 永不。此方法作用于全局,所有应用界面都会保持常亮,但可能影响整体续航。
-
代码层面:仅针对特定应用界面生效,比系统设置更灵活。可通过两种主流方式实现:
- 通过Window窗口标记:在Ability的
onWindowStageCreate或页面中获取顶端窗口对象(Window),调用setWindowKeepScreenOn(true)。 - 通过PowerManager:应用申请
ohos.permission.KEEP_BACKGROUND_RUNNING(或ohos.permission.RUNNING_LOCK)权限后,获取系统电源管理服务,创建并持有一个RUNNINGLOCK_BACKGROUND类型的锁。
- 通过Window窗口标记:在Ability的
代码方式下,应用切后台后锁可能被系统自动清理,仅保前台活跃界面的常亮。

