如何从 Fragment 清除 Android 中的 WindowManager 标志

sim*_*dam 5 android android-windowmanager android-activity

我有一FLAG_SECURE组活动(它包含敏感数据),但特别是Fragment我需要清除它(因为 od Android Beam)。

Window window = getActivity().getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
Run Code Online (Sandbox Code Playgroud)

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

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

Mir*_*ský 2

编辑:添加示例代码。

我来晚了,但无论如何我都会发布它。这不是最好的解决方案(以我的诚实观点),因为它在 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());
    }
}
Run Code Online (Sandbox Code Playgroud)

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