如何保持应用运行时不息屏

Heiang
发布于 2024-12-13 10:58
浏览
0收藏

问题场景

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

实现方案

​窗口系统提供了保持指定窗口屏幕常亮的接口 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%') 
  } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.


分类
收藏
回复
举报


回复
    相关推荐