Untitled
unknown
kotlin
14 days ago
3.3 kB
3
Indexable
package com.martitech.common.utils import android.content.Context import android.database.ContentObserver import android.net.Uri import android.os.Build import android.os.Handler import android.os.Looper import android.provider.MediaStore import android.util.Log class ScreenshotDetector( private val context: Context, private val block: () -> Unit ) : ContentObserver(Handler(Looper.getMainLooper())) { private val contentResolver = context.contentResolver fun startObserving() { contentResolver.registerContentObserver( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true, this ) } fun stopObserving() { contentResolver.unregisterContentObserver(this) } override fun onChange(selfChange: Boolean, uri: Uri?) { super.onChange(selfChange, uri) if (uri != null) { Log.d("ScreenshotDetector", "MediaStore change detected at $uri") detectScreenshotsForPreApi34(context) } } private fun detectScreenshotsForPreApi34(context: Context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { detectScreenshotsForScopedStorage(context) } else { detectScreenshotsLegacy(context) } } private fun detectScreenshotsLegacy(context: Context) { val projection = arrayOf( MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_ADDED ) val timeThreshold = (System.currentTimeMillis() / 1000) - 10 val selection = "${MediaStore.Images.Media.DATE_ADDED} >= ?" val selectionArgs = arrayOf(timeThreshold.toString()) val cursor = context.contentResolver.query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, selection, selectionArgs, "${MediaStore.Images.Media.DATE_ADDED} DESC" ) cursor?.use { if (it.moveToFirst()) { val imagePath = it.getString(it.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)) if (imagePath.contains("screenshot", true) || imagePath.contains("screen_capture", true)) { block.invoke() } } } } private fun detectScreenshotsForScopedStorage(context: Context) { val projection = arrayOf( MediaStore.Images.Media.RELATIVE_PATH, MediaStore.Images.Media.DATE_ADDED ) val timeThreshold = (System.currentTimeMillis() / 1000) - 10 val selection = "${MediaStore.Images.Media.DATE_ADDED} >= ?" val selectionArgs = arrayOf(timeThreshold.toString()) val cursor = context.contentResolver.query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, selection, selectionArgs, "${MediaStore.Images.Media.DATE_ADDED} DESC" ) cursor?.use { if (it.moveToFirst()) { val relativePath = it.getString(it.getColumnIndexOrThrow(MediaStore.Images.Media.RELATIVE_PATH)) if (relativePath.contains("Screenshots", true)) { block.invoke() } } } } }
Editor is loading...
Leave a Comment