HarmonyOS鸿蒙Next单页面防截屏示例代码

HarmonyOS鸿蒙Next单页面防截屏示例代码

介绍

本示例基于原生能力,实现对单个页面设置为隐私模式,使其可以禁止截屏,录屏及分享屏幕等行为。

单页面防截屏源码链接

效果预览

图片名称

实现思路

  1. onWindowStageCreate生命周期函数中获取windowClass对象并保存,在对应需要防截屏的页面获取对象并设置隐私模式:
windowStage.getMainWindow((err: BusinessError, data) => {
  let errCode: number = err.code;
  if (errCode) {
    console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err));
    return;
  }
  const windowClass = data;
  console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data));
  AppStorage.setOrCreate("windowClass",windowClass)
})
  1. 需要设置防截屏页面:
@State windowClass: window.Window | null | undefined = AppStorage.get('windowClass')
aboutToAppear(): void {
    let isPrivacyMode: boolean = true
    if (this.windowClass) {
      this.windowClass.setWindowPrivacyMode(isPrivacyMode); // 设置防截屏录屏
    }
}

更多关于HarmonyOS鸿蒙Next单页面防截屏示例代码的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

非常实用的场景,点赞

更多关于HarmonyOS鸿蒙Next单页面防截屏示例代码的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,可以通过设置页面的Window属性来防止截屏。以下是一个简单的示例代码:

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.window.service.WindowManager;

public class MainAbility extends Ability {
    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        // 获取当前窗口
        WindowManager.getInstance().getTopWindow().ifPresent(window -> {
            // 设置窗口属性,禁止截屏
            window.addFlags(WindowManager.LayoutConfig.MARK_SECURE);
        });
    }
}

这段代码在onStart方法中获取当前窗口,并通过addFlags方法设置MARK_SECURE标志,从而防止该页面被截屏。

回到顶部