HarmonyOS 鸿蒙Next应用如何设置屏幕常亮?
HarmonyOS 鸿蒙Next应用如何设置屏幕常亮? 金融类或钱包场景的应用APP,对于付款码,扫一扫等场景都会对屏幕设置常亮。防止屏幕长时间不操作,自动息屏。
目前这种场景的需求也是非常有必要的,也是行业内默认的处理方式。
那屏幕常亮在鸿蒙中如何实现呢?
获取窗口实例对象后,调用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));
}
参考链接
更多关于HarmonyOS 鸿蒙Next应用如何设置屏幕常亮?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
通过接口setWindowKeepScreenOn(isKeepScreenOn: boolean, callback: AsyncCallback<void>): void
设置屏幕是否为常亮状态。
注意:规范使用该接口:仅在必要场景(导航、视频播放、绘画、游戏等场景)下,设置该属性为true;退出上述场景后,应当重置该属性为false;其他场景(无屏幕互动、音频播放等)下,不使用该接口;系统检测到非规范使用该接口时,可能会恢复自动灭屏功能。
系统能力: SystemCapability.WindowManager.WindowManager.Core
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| isKeepScreenOn | boolean | 是 | 设置屏幕是否为常亮状态。true表示常亮;false表示不常亮。 |
| callback | AsyncCallback<void> | 是 | 回调函数。 |
先使用getLastWindow()、createWindow()、findWindow()中的任一方法获取到Window实例(windowClass),再通过此实例调用对应方法。
import { window } from ‘@kit.ArkUI’;
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中,设置屏幕常亮需在应用的module.json5配置文件中声明ohos.permission.KEEP_SCREEN_ON权限。然后在需要常亮的Ability或UI组件中,调用window模块的setWindowKeepScreenOn方法,并传入true参数即可实现。
在HarmonyOS Next中,可以通过Window对象的setWindowKeepScreenOn()方法来实现屏幕常亮。这是推荐的方式,因为它允许系统在合适的时机(例如应用进入后台时)管理此行为,有助于节省电量。
核心实现步骤:
- 获取当前窗口:首先需要获取应用当前顶部的窗口对象。
- 设置常亮标志:调用窗口的
setWindowKeepScreenOn(true)方法。 - (可选)取消设置:在不需要常亮的场景(如离开付款码页面),调用
setWindowKeepScreenOn(false)来恢复系统的自动息屏策略。
示例代码:
import { window } from '@kit.ArkUI';
// 1. 在需要设置屏幕常亮的页面(例如付款码页面的aboutToAppear或按钮事件中)
let currentWindow = window.getLastWindow(this.context); // 获取当前窗口
currentWindow.setWindowKeepScreenOn(true); // 设置屏幕常亮
// 2. 在页面退出或特定条件下(例如aboutToDisappear),取消常亮设置
currentWindow.setWindowKeepScreenOn(false);
关键说明:
- 生命周期管理:务必在适当的生命周期(如
aboutToDisappear)或事件中取消常亮设置,避免影响应用其他页面或耗电。 - 作用范围:此设置作用于该应用窗口。当窗口销毁(如应用退到后台)或主动取消后,效果消失。
- 权限:此操作通常不需要额外声明权限。
对于金融、支付类场景,建议在付款码展示、扫码等核心交互页面启用,并在页面退出时立即关闭,以符合HarmonyOS的应用规范。


