You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NativeScript移动应用中禁用截图?Android原生FLAG_SECURE代码如何使用?

在NativeScript移动应用中禁用截图(Android平台)

你已经知道原生Android里用getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE)就能禁用截图,在NativeScript里其实就是通过它的原生桥接能力调用这段代码就行,下面分两种常见场景给你具体实现方案:

一、全局禁用截图(整个应用所有页面都禁用)

如果希望打开应用后所有页面都禁止截图,可以在应用启动的时机设置这个标志:

TypeScript 代码示例

import { Application } from "@nativescript/core";

// 监听应用启动完成事件
Application.on(Application.launchEvent, () => {
    // 只在Android平台执行
    if (Application.android) {
        // 获取应用的主Activity
        const mainActivity = Application.android.startActivity;
        // 获取Activity对应的Window对象
        const window = mainActivity.getWindow();
        // 引用Android的LayoutParams类
        const LayoutParams = android.view.WindowManager.LayoutParams;
        // 设置FLAG_SECURE标志
        window.setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);
    }
});

JavaScript 代码示例

const { Application } = require("@nativescript/core");

Application.on(Application.launchEvent, () => {
    if (Application.android) {
        const mainActivity = Application.android.startActivity;
        const window = mainActivity.getWindow();
        const LayoutParams = android.view.WindowManager.LayoutParams;
        window.setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);
    }
});

二、单个页面禁用截图(仅特定页面禁止)

如果只需要在某个特定页面禁用截图,可以在页面的loaded事件中处理:

页面XML代码

<Page xmlns="http://schemas.nativescript.org/tns.xsd" loaded="onPageLoaded">
    <!-- 你的页面内容 -->
</Page>

TypeScript 逻辑代码

import { Page } from "@nativescript/core";
import { Application } from "@nativescript/core";

export function onPageLoaded(args) {
    const page = args.object as Page;
    if (Application.android) {
        // 获取当前页面对应的Android Context(即Activity)
        const currentActivity = page.android.context;
        const window = currentActivity.getWindow();
        const LayoutParams = android.view.WindowManager.LayoutParams;
        window.setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);
    }
}

取消禁用截图

如果之后需要恢复截图功能,只需要调用clearFlags方法移除标志即可:

window.clearFlags(android.view.WindowManager.LayoutParams.FLAG_SECURE);

补充:iOS平台禁用截图

如果你也需要兼容iOS,NativeScript同样可以调用原生API实现:

import { Page } from "@nativescript/core";

export function onPageLoaded(args) {
    const page = args.object as Page;
    if (page.ios) {
        // iOS 13+ 支持的API
        page.ios.viewController.preventsScreenCapture = true;
    }
}

内容的提问来源于stack exchange,提问作者Ivan Paschenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:40:38