【问题标题】:How to clear WindowManager flags in Android from Fragment如何从 Fragment 清除 Android 中的 WindowManager 标志
【发布时间】:2015-03-31 13:46:31
【问题描述】:

我为一项活动设置了FLAG_SECURE(它包含敏感数据),但在一个特定的Fragment 中我需要清除它(因为 Android Beam)。

Window window = getActivity().getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE);

此代码清除标志(我在 Fragment 的 onResume 回调中有它),但问题是,它在下一次配置更改(屏幕旋转,...)之前不会生效 同样的问题是在离开 Fragment 时再次设置标志。

有谁知道,我该怎么做才能解决这个问题? (我考虑过Activity.recreate(),它可以工作,但我不喜欢这个解决方案) 如果可能,我不想为此特定屏幕创建单独的Activity

【问题讨论】:

    标签: android android-activity android-windowmanager


    【解决方案1】:

    编辑:添加示例代码。

    我在这里迟到了,但无论如何我都会发布它。这不是最好的解决方案(以我的诚实观点),因为它在 Android 4.x 上产生了可见的“重新绘制”效果(5+ 很好),但它至少可以工作。我是这样使用它的:

    /**
     * @param flagSecure adds/removes FLAG_SECURE from Activity this Fragment is attached to/from.
     */
    public void applyFlagSecure(boolean flagSecure)
    {
        Window window = getActivity().getWindow();
        WindowManager wm = getActivity().getWindowManager();
    
        // is change needed?
        int flags = window.getAttributes().flags;
        if (flagSecure && (flags & WindowManager.LayoutParams.FLAG_SECURE) != 0) {
            // already set, change is not needed.
            return;
        } else if (!flagSecure && (flags & WindowManager.LayoutParams.FLAG_SECURE) == 0) {
            // already cleared, change is not needed.
            return;
        }
    
        // apply (or clear) the FLAG_SECURE flag to/from Activity this Fragment is attached to.
        boolean flagsChanged = false;
        if (flagSecure) {
            window.addFlags(WindowManager.LayoutParams.FLAG_SECURE);
            flagsChanged = true;
        } else {
            // FIXME Do NOT unset FLAG_SECURE flag from Activity's Window if Activity explicitly set it itself.
            if (!(getActivity() instanceof YourFlagSecureActivity)) {
                // Okay, it is safe to clear FLAG_SECURE flag from Window flags.
                // Activity is (probably) not showing any secure content.
                window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
                flagsChanged = true;
            }
        }
    
        // Re-apply (re-draw) Window's DecorView so the change to the Window flags will be in place immediately.
        if (flagsChanged && ViewCompat.isAttachedToWindow(window.getDecorView())) {
            // FIXME Removing the View and attaching it back makes visible re-draw on Android 4.x, 5+ is good.
            wm.removeViewImmediate(window.getDecorView());
            wm.addView(window.getDecorView(), window.getAttributes());
        }
    }
    

    来源:此解决方案基于 kdas 的示例:How to disable screen capture in Android fragment?

    【讨论】:

    • 请从链接中添加一些内容
    猜你喜欢
    • 1970-01-01
    • 2021-03-01
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 2014-09-12
    相关资源
    最近更新 更多