Prevent Screenshots in Android

Photo by ShengGeng Lin on Unsplash
Photo by ShengGeng Lin on Unsplash
For some reasons, we may want to prevent users from taking screenshots of our app. In Android, we can use WindowManager.LayoutParams.FLAG_SECURE to achieve this effect.

For some reasons, we may want to prevent users from taking screenshots of our app. In Android, we can use WindowManager.LayoutParams.FLAG_SECURE to achieve this effect. In the code below, we only need to set WindowManager.LayoutParams.FLAG_SECURE in Activity.onCreate().

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        window.setFlags(
            WindowManager.LayoutParams.FLAG_SECURE,
            WindowManager.LayoutParams.FLAG_SECURE,
        )
    }
}

If the user takes a screenshot on the screen with WindowManager.LayoutParams.FLAG_SECURE set, the system will automatically display the message “The app doesn’t allow taking screenshots”.

After setting WindowManager.LayoutParams.FLAG_SECURE, you can also use the code below to clear this flag at any time.

window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)

Finally, it should be noted that this WindowManager.LayoutParams.FLAG_SECURE will only affect the current Activity. If you want to prevent screenshots for every Activity, you can set WindowManager.LayoutParams.FLAG_SECURE in ActivityLifecycleCallbacks.onActivityCreated().

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
   
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                activity.window.setFlags(
                    WindowManager.LayoutParams.FLAG_SECURE,
                    WindowManager.LayoutParams.FLAG_SECURE
                )
            }

            override fun onActivityStarted(activity: Activity) {}
            override fun onActivityResumed(activity: Activity) {}
            override fun onActivityPaused(activity: Activity) {}
            override fun onActivityStopped(activity: Activity) {}
            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
            override fun onActivityDestroyed(activity: Activity) {}
        })
    }
}
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like