Search code examples
androidandroid-fragmentsscreenshotlayoutparams

How to disable screen capture in Android fragment?


Is it possible to disable screen capture from a fragment? I know the below works for an Activity class

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

But what if I have a fragment which shows up on top of an activity. Can I somehow disable screen capture? I've tried to set the FLAG_SECURE in the onCreate() or onCreateView() method of the fragment, but it doesn't work. I'm still able to take screen shot. Only when I add the flag in parent activity I can disable it.

On a related note, say, I've a method in ParentActivity.java (which extends Activity)

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

}

And in my ChildFragment.java (which extends 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
    }

Any ideas?

Thanks in advance


Solution

  • The below code worked for me.

    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());
    
    }