官方给的demo里面主要是针对window窗口进行的一个禁止截屏,相当于整个应用都无法去截屏了。关键属性 setWindowPrivacyMode()第一参数是个布尔值,false代表关闭禁止截屏,ture,代表打开,第二个参数是个回调
第二个:开启权限 在module.json5里面去开启
"requestPermissions":{ "name": "ohos.permission.PRIVACY_WINDOW" },
整体的思路主要是获取Windows的实例,然后在进入和离开页面的生命周期去调用里面的方法,进行一个实现
思路一:页面设置禁止截屏的开启和关闭,进入页面在 onpageshow生命周期里面调取开启禁止截屏方法,为什么不是aboutToAppear? 当你返回上个页面的时候是不会去走aboutToAppear这个生命周期的
页面离开用onPageHide调用关闭禁止截屏方法,
private context: common.BaseContext = getContext(this) as common.BaseContext
screenshots(bol: boolean) {
window.getLastWindow(this.context)
.then((windowClass: window.Window) => {
try {
windowClass.setWindowPrivacyMode(bol, (err: BusinessError) => {
const errCode: number = err.code;
if (errCode) {
console.error(`Failed to set the window to privacy mode. Cause code: ${err.code}, message: ${err.message}`);
return;
}
console.info('Succeeded in setting the window to privacy mode.');
});
} catch (exception) {
console.error(`Failed to set the window to privacy mode. Cause code: ${exception.code}, message: ${exception.message}`);
}
})
.catch(() => {
})
}
思路二:在EntryAbility 里面获取windowclass ,然后用
AppStorage.setOrCreate('windowStage',windowClass);全局变量,后面就可以在需要的页面去使用,
@StorageLink('windowStage') windowClass?:window.Window=AppStorage.get('windowStage')
需要禁止截屏的页面里面去使用,同样也是在上述的两个生命周期里面去使用
(this.windowClass as window.Window).setWindowPrivacyMode(true,(err: BusinessError)=>{ const errCode: number = err.code;
if (errCode) {
console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(err));
return;
}
})