Last active
May 13, 2024 01:00
-
-
Save ksharma-xyz/f6d705aa1515806561aff663c907f8c6 to your computer and use it in GitHub Desktop.
Listen to changes in android Lifecycle in Composable and set and clear secure flag in onStart / onStop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.app.Activity | |
import android.content.Context | |
import android.content.ContextWrapper | |
import android.view.WindowManager.LayoutParams.FLAG_SECURE | |
import androidx.compose.foundation.background | |
import androidx.compose.foundation.layout.Box | |
import androidx.compose.foundation.layout.fillMaxSize | |
import androidx.compose.material3.Text | |
import androidx.compose.runtime.Composable | |
import androidx.compose.ui.Alignment | |
import androidx.compose.ui.Modifier | |
import androidx.compose.ui.graphics.Color | |
import androidx.compose.ui.platform.LocalContext | |
import androidx.lifecycle.Lifecycle | |
import androidx.lifecycle.lifecycleScope | |
import kotlinx.coroutines.delay | |
import kotlinx.coroutines.launch | |
import java.lang.IllegalStateException | |
@Composable | |
fun SecureScreen() { | |
val context: Context = LocalContext.current | |
val activity = context.findActivity() | |
SecureScreenContent(modifier = Modifier.fillMaxSize()) | |
ComposableLifecycleListener { source, event -> | |
when (event) { | |
Lifecycle.Event.ON_START -> activity.window.setFlags(FLAG_SECURE, FLAG_SECURE) | |
Lifecycle.Event.ON_STOP -> { | |
source.lifecycleScope.launch { | |
/* | |
Add a small delay to ensure we have navigated away from the secure screen. | |
Otherwise, it will still be visible during screen recording. | |
*/ | |
delay(200) | |
activity.window.clearFlags(FLAG_SECURE) | |
} | |
} | |
else -> Unit | |
} | |
} | |
} | |
@Composable | |
private fun SecureScreenContent(modifier: Modifier) { | |
Box( | |
modifier = modifier.background(color = Color.Red), | |
contentAlignment = Alignment.Center | |
) { | |
Text(text = "Secure Screen") | |
} | |
} | |
fun Context.findActivity(): Activity { | |
var context = this | |
while (context is ContextWrapper) { | |
if (context is Activity) return context | |
context = context.baseContext | |
} | |
throw IllegalStateException("Activity not found") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment