Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 15611

Taking screenshot programtically in android, but not visible in storage

$
0
0

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..

  1. Asking for media permission.
  2. Get the rootview.
  3. Storing it in a bitmap
  4. 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()    }}

Viewing all articles
Browse latest Browse all 15611

Trending Articles