2

On Android 12, if I create an simple app with WindowManager.LayoutParams.FLAG_SECURE

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setFlags(
            WindowManager.LayoutParams.FLAG_SECURE,
            WindowManager.LayoutParams.FLAG_SECURE
        )
        setContentView(R.layout.activity_main)
    }
}

the window does not secure if I try to switch apps

enter image description here

however, if I switch back, the window does secure

enter image description here

In both cases, switching to or from, the window secures on Android 11, but not on Android 12. Any idea why?

the_prole
  • 8,275
  • 16
  • 78
  • 163

3 Answers3

3

Easy approach using View#onWindowFocusChanged(boolean) on your Activity:

@Override
public void onWindowFocusChanged(boolean hasFocus) {
  super.onWindowFocusChanged(hasFocus);
  if (hasFocus) {
    // allow screenshots when activity is focused
    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
  } else {
    // hide information (blank view) on app switcher
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
  }
}
Aure77
  • 3,034
  • 7
  • 33
  • 53
2

As of Android version 12, it was the desired behavior. additionally, you can check the Google Issue Tracker.

https://issuetracker.google.com/issues/237190495

Instead of onPause and onResume, we can use onWindowFocusChanged(boolean).when the activity does not have focus we can enable FLAG_SECURE when the app does regain focus we can clear FLAG_SECURE

AmarDurai
  • 91
  • 1
  • 8
0

A new flag is added in Android 13 to prevent the app preview from appearing in the Recent Apps. https://developer.android.com/reference/android/app/Activity#setRecentsScreenshotEnabled(boolean) Although this is not for Android 12, I am sharing here for people who are interested in this feature.