问题场景

在一些特殊应用场景下,例如视频播放、语音播放、地图导航期间,即使用户没有屏幕交互操作,也不希望手机跟随系统设置的休眠时间自动熄屏,而是保持屏幕常亮,直至完成或退出相关场景。

实现方案

窗口系统提供了保持指定窗口屏幕常亮的接口 windowClass.setWindowKeepScreenOn(isKeepScreenOn: boolean, callback: AsyncCallback<void\>): void,windowClass表示窗口实例,第一个参数 isKeepScreenOn 表示是否保持屏幕常亮。

需要注意在恰当时机开启屏幕常亮的同时,要记得在场景中断或退出的时候关闭屏幕常亮。例如视频播放开始(包括进入视频页面自动开始播放)时,开启屏幕常亮;在视频暂停播放或页面退出时,关闭屏幕常亮。

示例代码如下:

import { BusinessError } from '@kit.BasicServicesKit';
import { window } from '@kit.ArkUI';
import { common } from '@kit.AbilityKit';

@Entry
@Component
struct PageVideo {
  @State isKeepScreenOn: boolean = true
  aboutToAppear(): void {
    this.keepScreenOn()
  }

  aboutToDisappear(): void {
    this.isKeepScreenOn = false
    this.keepScreenOn()
  }

  keepScreenOn() {
    // 获取窗口实例
    const windowStage = (getContext() as common.UIAbilityContext).windowStage;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      const mainWindow: window.Window = data;

      // 设置屏幕是否常亮
      mainWindow?.setWindowKeepScreenOn(this.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.');
      });
    })
  }

  build() {
    Column() {
      Text(this.isKeepScreenOn ? "点击暂停,取消常亮" : "点击播放,开启常亮")
        .fontSize(50)
        .height(200)
        .fontWeight(FontWeight.Bold)
        .onClick(() => {
          this.isKeepScreenOn = !this.isKeepScreenOn
          this.keepScreenOn()
        })
    }
    .height('100%')
    .width('100%')
  }
}

HarmonyOS码上奇行
11.9k 声望4.2k 粉丝

欢迎关注 HarmonyOS 开发者社区:[链接]