Reputation: 8945
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
however, if I switch back, the window does secure
In both cases, switching to or from, the window secures on Android 11, but not on Android 12. Any idea why?
Upvotes: 4
Views: 10537
Reputation: 658
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
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) {
window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
} else {
window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
}
}
Upvotes: 3
Reputation: 89
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.
Upvotes: 3
Reputation: 3209
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);
}
}
Upvotes: 7