I am have wrote the following code to take the screenshot in jetpakc compose. But the file is not visible in the storage, can anybody please help me to identify what i am doing wrong..
- Asking for media permission.
- Get the rootview.
- Storing it in a bitmap
- Writing that to a file.
class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { var isPermission by remember { mutableStateOf(false) } val context : Context = this val mediaStoragePermission = rememberLauncherForActivityResult( contract = ActivityResultContracts.RequestPermission(), onResult = {isGranted -> if(isGranted) { isPermission = true; Toast.makeText(context, "Permission granted", Toast.LENGTH_SHORT).show() } } ) Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Button(onClick = {mediaStoragePermission.launch( android.Manifest.permission.WRITE_EXTERNAL_STORAGE ) }) { Text(text = "Take ScreenShot") } } if(isPermission) { ScreenshotComponent() } } }}
Screenshot component
@Composablefun ScreenshotComponent() { val view = LocalView.current val context = LocalContext.current val handler = Handler(Looper.getMainLooper()) handler.postDelayed(Runnable { val bmp = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888).applyCanvas { view.draw(this) } bmp.let { File(context.filesDir, "screenshot.png") .writeBitmap(bmp, Bitmap.CompressFormat.PNG, 85) } }, 1000)}private fun File.writeBitmap(bitmap: Bitmap, format: Bitmap.CompressFormat, quality: Int) { outputStream().use { out -> bitmap.compress(format, quality, out) out.flush() }}