HarmonyOS鸿蒙Next中实现页面隐私模式示例代码

发布于 1周前 作者 eggper 来自 鸿蒙OS

HarmonyOS鸿蒙Next中实现页面隐私模式示例代码

介绍

本示例基于setWindowPrivacyMode接口实现了将页面设置为禁止截屏或录屏的隐私模式。

实现页面隐私模式源码链接

效果预览

图片名称

使用说明

点击“开启隐藏”按钮,进入隐私模式,截屏时会出现弹窗提示,禁止截屏,录屏时会隐藏页面。点击“关闭隐藏”按钮,将退出隐私模式。

实现思路

通过setWindowPrivacyMode接口设置窗口是否为隐私模式,使用callback异步回调,设置为隐私模式的窗口,窗口内容将无法被截屏或录屏。核心代码如下,源码参考Index.ets。

Button() {
    Text('开启隐藏');
}
.width(80)
.height(60)
.onClick(() => {
    let isPrivacyMode: boolean = true;
    try {
        window.getLastWindow(getContext(), (err: BusinessError, data) => {
            const errCode = err.code;
            if (errCode) {
                return;
            }
            let promise = data.setWindowPrivacyMode(isPrivacyMode);
            promise.then(() => {
                this.message = '隐私模式';
                hilog.info(0x0000, 'testTag', '已成功将窗口设置为隐私模式.');
            }).catch((err: BusinessError) => {
                hilog.error(0x0000, 'testTag', 'Failed to set the window to privacy mode. Cause: ' + JSON.stringify(err));
            });
        });
    } catch (exception) {
        hilog.error(0x0000, 'testTag', 'Failed to set the window to privacy mode. Cause:' + JSON.stringify(exception));
    }
});

更多关于HarmonyOS鸿蒙Next中实现页面隐私模式示例代码的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

在HarmonyOS鸿蒙Next中实现页面隐私模式,可以通过以下代码示例进行演示:

import { PrivacyManager, WindowManager } from '@ohos.application.WindowManager';

class PrivacyPage {
  private privacyManager: PrivacyManager;
  private windowManager: WindowManager;

  constructor() {
    this.privacyManager = new PrivacyManager();
    this.windowManager = new WindowManager();
  }

  public enablePrivacyMode(): void {
    this.privacyManager.enablePrivacyMode();
    this.windowManager.setWindowFlags(WindowManager.FLAG_SECURE);
  }

  public disablePrivacyMode(): void {
    this.privacyManager.disablePrivacyMode();
    this.windowManager.clearWindowFlags(WindowManager.FLAG_SECURE);
  }
}

// 使用示例
const privacyPage = new PrivacyPage();
privacyPage.enablePrivacyMode(); // 启用隐私模式
privacyPage.disablePrivacyMode(); // 禁用隐私模式

在上述代码中,PrivacyManager 用于管理隐私模式,WindowManager 用于设置窗口标志。通过调用 enablePrivacyMode 方法,可以启用隐私模式,防止敏感信息被截屏或录屏。调用 disablePrivacyMode 方法则可以禁用隐私模式。

更多关于HarmonyOS鸿蒙Next中实现页面隐私模式示例代码的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,可以通过设置页面的privacyMode属性来实现隐私模式。以下是一个简单的示例代码:

import { UIAbility } from '@ohos.ability.UIAbility';
import { window } from '@ohos.window';

export default class EntryAbility extends UIAbility {
    onCreate() {
        let windowClass = window.getLastWindow(this.context);
        windowClass.then((win) => {
            // 设置页面为隐私模式
            win.setWindowPrivacyMode(true);
        });
    }
}

这段代码在应用启动时,将当前窗口设置为隐私模式。在隐私模式下,系统会模糊或隐藏页面内容,以保护用户隐私。

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!