FLAG SECURE not working with Jetpack Lifecycle events

1.5k Views Asked by At

As per the requirement, we have to hide the App's last stored state/snap when viewed from app carousel in minimized state. Now in the app, I'm using JetPack's lifecycle events - ON_START and ON_STOP in order to detect the state if the app going in background or coming to foreground. Here is the code snippet for reference -

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        public void onAppBackgrounded() {
            //App in background
           getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE))
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        public void onAppForegrounded() {
            // App in foreground
         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE)) 
        }

So basically what I'm trying to do here is - I'm enabling flag secure when app goes to background and disabling it when it comes back to foreground in order to allow app to take screenshots. As by using flag secure, Android by default will disable the user to take app screenshots.

This is working perfectly with onPause and onResume. Is there any way where we can make it work using Lifecycle events? Thanks.

1

There are 1 best solutions below

0
Peter On

the same experience, works if you call

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

in onCreate() of the activity, before calling "setContent"