护眼功能是很多app的一个常见功能,那么具体到HarmonyOS该如何实现该功能呢?
废话不多说,直接上代码:
/*创建护眼模式子窗口
backgroundColor:需要设置的护眼模式背景颜色
this.windowStage:备注,我这里是使用单列进行的,在EntryAbility类的onWindowStageCreate方法中,
将windowStage赋值给单列的属性windowStage。在app首页或其他按钮点击触发来调用createSubWithEyeWindow方法进行护眼模式的触发
*/
createSubWithEyeWindow(backgroundColor: string): void {
if (this.windowStage == null) {
console.error('windowStage为空,请先传值后再创建')
} else {
// 创建子窗口
this.windowStage.createSubWindow('eyeWindow', (error: BusinessError, data) => {
let errCode = error.code
if (errCode) {
console.error('创建护眼模式window失败:', json.stringify(error))
return
}
// private eye_windowClass: window.Window | null = null; 单列设置的属性
this.eye_windowClass = data
console.log('创建护眼模式window成功')
// 2、设置全屏显示
this.eye_windowClass?.setWindowLayoutFullScreen(true)
//3、设置不可触摸,防止护眼模式窗口阻挡主窗口的手势
this.eye_windowClass.setWindowTouchable(false)
//4、设置window的承载content,必须设置,否则会显示失败
//下面是页面路由路径的获取,appBundleName方法已在下面贴出,TBXBaseLib是我自己的具体组件模块名:
const pagePath = 'ets/pages/EyeContentPage.ets'
let url = `@bundle:${ApplicationUtil.appBundleName()}/TBXBaseLib/${pagePath}`
this.eye_windowClass.setUIContent(url, (err: BusinessError) => {
// 5.设置背景颜色
if (!err.code) {
this.eye_windowClass?.setWindowBackgroundColor(backgroundColor)
}
})
//6、显示窗口
this.eye_windowClass?.showWindow((err: BusinessError) => {
let errCode: number = err.code;
if (errCode) {
console.error('Failed to show the window. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in showing the window.');
})
})
}
}
/*移除护眼模式子窗口*/
removeSubWithEyeWindow(): void {
if (this.eye_windowClass != null) {
this.eye_windowClass.destroyWindow((error: BusinessError) => {
let errCode = error.code
if (errCode) {
console.error('Failed to destroy the window. Cause: ' + JSON.stringify(error));
return;
}
console.info('Succeeded in destroying the window.');
this.eye_windowClass = null
})
}
}
/**
* 获取app bundleName
*/
public appBundleName(): string {
return bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)
.appInfo
.descriptionResource
.bundleName
}
好啦,护眼模式就搞定啦
网友评论