android-fragments 如何在Android片段中禁用屏幕捕捉?

k3bvogb1  于 2022-11-13  发布在  Android
关注(0)|答案(3)|浏览(211)

有没有可能从片段中禁用屏幕捕获?我知道下面的方法适用于Activity类

onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
                WindowManager.LayoutParams.FLAG_SECURE);
}

但如果我有一个片段显示在Activity的顶部,该怎么办?我可以禁用屏幕捕获吗?我尝试在片段的onCreate()或onCreateView()方法中设置FLAG_SECURE,但它不起作用。我仍然可以进行屏幕捕获。只有当我在父Activity中添加标志时,我才可以禁用它。
与此相关的是,我在www.example.com中有一个方法ParentActivity.java(它扩展了Activity)

public void disableScreenCapture() {
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
            WindowManager.LayoutParams.FLAG_SECURE);

}

而在我的ChildFragment.java(它扩展了Fragment)中

public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                ParentActivity parentActivity = (ParentActivity)getActivity();
                parentActivity.disableScreenCapture(); //doesn't work
        }
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
                ParentActivity parentActivity = (ParentActivity)getActivity();
                parentActivity.disableScreenCapture(); //doesn't work either
    }

有什么想法吗?
先谢谢你

zrfyljdw

zrfyljdw1#

在片段中的onResumeonCreateViewonActivityAttached中执行disableScreenCapture()调用应该都可以, -它们对我来说是有效的。在onActivityCreated中执行该调用可能不起作用,因为我相信只有在Activity被销毁后 * 重新 *-创建时才会调用该钩子。但是,我没有尝试过那个。
如果在onCreateView中执行该调用对您不起作用,您是否100%确定您的Fragment实际上被添加到了Activity中?
对于DialogFragment,则略有不同:

getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
        WindowManager.LayoutParams.FLAG_SECURE);

DialogFragment本身并不是Dialog,而是包含一个对Dialog的引用,并在添加或删除片段时显示/取消它。对话框有自己的窗口,必须单独设置标志。

lzfw57am

lzfw57am2#

下面的代码对我有效。

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    getActivity().getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);
    Window window = getActivity().getWindow();
    WindowManager wm = getActivity().getWindowManager();
    wm.removeViewImmediate(window.getDecorView());
    wm.addView(window.getDecorView(), window.getAttributes());

}
bfrts1fy

bfrts1fy3#

您可以在Parent Activity中创建一个公共函数,并设置fragment的onAttach方法中的标志,并清除onDetach方法中的标志。
父活动中的方法

fun disableScreenShot(isSecure:Boolean){
    if (isSecure) {
        window.setFlags(WindowManager.LayoutParams.FLAG_SECURE,
            WindowManager.LayoutParams.FLAG_SECURE);
    }
    else{
        window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
    }
}

片段中的代码

override fun onAttach(context: Context) {
        super.onAttach(context)
        activity = context as HomeActivity
        activity.disableScreenShot(true)
    }

    override fun onDetach() {
        super.onDetach()
        activity.disableScreenShot(false)
    }

相关问题