Black Screen while Using Windowmanager.LayoutParams.FLAG_SECURE in google pixel 6 (android >= 11)
I face a black screen whenever I use Windowmanager.LayoutParams.FLAG_SECURE to prevent screenshot and screen recordings on a device. This bug happens in specific devices like Google Pixel 6, Oppo, and Vivo.
The following app activates Windowmanager.LayoutParams.FLAG_SECURE on clicking a button and then screen turns black. The code is below: -
App.js: -
/* eslint-disable react/react-in-jsx-scope */
import {Button, StyleSheet, View} from 'react-native';
import * as ScreenCapture from 'expo-screen-capture';
export default function ScreenCaptureExample() {
const activate = async () => {
await ScreenCapture.preventScreenCaptureAsync();
};
const deactivate = async () => {
await ScreenCapture.allowScreenCaptureAsync();
};
return (
<View style={styles.container}>
<View>
<Button title="Activate" onPress={activate} />
<Button title="Deactivate" onPress={deactivate} />
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
});
ScreenCaptureAndroid.js: -
import * as ScreenCapture from 'expo-screen-capture';
const allowScreenCapture = async () => {
try {
await ScreenCapture.allowScreenCaptureAsync();
} catch (e) {}
};
const disableScreenCapture = async () => {
try {
await ScreenCapture.preventScreenCaptureAsync();
} catch (e) {}
};
const func = {
allowScreenCapture,
disableScreenCapture,
};
export default func;
ScreenCaptureModule.kt (File from expo-screen-capture node_modules folder): -
package expo.modules.screencapture
import android.view.Display
import android.content.Context
import android.view.WindowManager
import expo.modules.kotlin.exception.Exceptions
import expo.modules.kotlin.functions.Queues
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
class ScreenCaptureModule : Module() {
private val context: Context
get() = appContext.reactContext ?: throw Exceptions.AppContextLost()
private val currentActivity
get() = appContext.currentActivity ?: throw Exceptions.MissingActivity()
override fun definition() = ModuleDefinition {
Name("ExpoScreenCapture")
OnCreate {
ScreenshotEventEmitter(context, appContext.legacyModuleRegistry)
}
AsyncFunction("preventScreenCapture") {
currentActivity.window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
}.runOnQueue(Queues.MAIN)
AsyncFunction("allowScreenCapture") {
currentActivity.window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
}.runOnQueue(Queues.MAIN)
}
}