Skip to content

Instantly share code, notes, and snippets.

@ForceGT
Last active December 7, 2023 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ForceGT/4d4faa3318b22dac5638c7ba467795a3 to your computer and use it in GitHub Desktop.
Save ForceGT/4d4faa3318b22dac5638c7ba467795a3 to your computer and use it in GitHub Desktop.
Screenshot detection observer for Android 14+, without tying the logic to a specific activity
object ScreenshotUtils {
private lateinit var screenCaptureCallback: Activity.ScreenCaptureCallback
fun Activity.observeScreenShotDetection(onScreenShotDetected: () -> Unit) {
// TODO Add API Check here
(this as LifecycleOwner).lifecycle.addObserver(
object : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) {
screenCaptureCallback = Activity.ScreenCaptureCallback(onScreenShotDetected)
this@observeScreenShotDetection.registerScreenCaptureCallback(mainExecutor, screenCaptureCallback)
}
override fun onStop(owner: LifecycleOwner) {
this@observeScreenShotDetection.unregisterScreenCaptureCallback(screenCaptureCallback)
}
})
}
// Call this method from Activity / Fragment
// Fragment
// requireActivity().observeScreenShotDetection{
// Add code here
// }
//
// Activity
// this.observerScreenShotDetection{
// Do something here
// }
//
@ForceGT
Copy link
Author

ForceGT commented Dec 7, 2023

Don't forget to add the permission in the manifest, and surround the above code with the permission check,otherwise it might crash

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment