Skip to main content

Code

Helper code related to screenshots.

ScreenshotUtil.kt
package com.hanmajid.androidnotebook

import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.os.Build
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import android.view.PixelCopy
import android.view.Window
import android.view.WindowManager

/**
* Screenshot-related utility object.
*/
object ScreenshotUtil {

/**
* Returns true if [window] is currently protected from screenshot.
*/
fun isScreenshotPreventionEnabled(window: Window): Boolean {
return (window.attributes.flags and WindowManager.LayoutParams.FLAG_SECURE) != 0
}

/**
* Enable screenshot prevention on [window].
*/
fun enableScreenshotPrevention(window: Window) {
window.setFlags(
WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE,
)
}

/**
* Disable screenshot prevention on [window].
*/
fun disableScreenshotPrevention(window: Window) {
window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
}

/**
* Take a screenshot of current [Activity].
*/
fun takeScreenshot(
activity: Activity,
) {
val view = activity.window.decorView.rootView
val resultBitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val thread = HandlerThread("MyThread").apply {
start()
}
val handler = Handler(thread.looper)
PixelCopy.request(
activity.window,
resultBitmap,
{
if (it == PixelCopy.SUCCESS) {
saveScreenshot(
activity = activity,
bitmap = resultBitmap,
filename = "my-screenshot-pixel-copy.png",
)
} else {
Log.i("TAG", "ERROR $it")
// Handle error.
}
},
handler,
)
} else {
val canvas = Canvas(resultBitmap)
activity.runOnUiThread {
try {
view.draw(canvas)
saveScreenshot(
activity = activity,
bitmap = resultBitmap,
filename = "my-screenshot-canvas.png",
)
} catch (e: Throwable) {
Log.e("TAG", e.message, e)
// Handle error.
}
}
}
}

/**
* Save the taken screenshot [bitmap] to internal storage.
*/
private fun saveScreenshot(
activity: Activity,
bitmap: Bitmap,
filename: String,
) {
activity.openFileOutput(filename, Context.MODE_PRIVATE)
.use { outputStream ->
bitmap.compress(Bitmap.CompressFormat.PNG, 0, outputStream)
}
}
}