In my application I am using `LocalContext.Current...
# compose
n
In my application I am using
LocalContext.Current
for some process where I take a screenshot and share it. I have a memory leak and I think this whole process is the cause. Is there a way in which I can dispose of the context when I navigate back to the Homescreen? I thought I could use
DisposableEffect
but I can't seem to make it happen (I can't work out how to use it here). I'll put my code in the thread. Thanks.
Here is my code:
Copy code
IconButton(onClick = {
        coroutineScope.launch {
            // Take Screenshot
            val handler = Handler(Looper.getMainLooper())
            handler.postDelayed({
                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)

            // Share Screenshot
            val contentUri = FileProvider.getUriForFile(
                Objects.requireNonNull(context),
                BuildConfig.APPLICATION_ID + ".provider",
                File(context.filesDir, "screenshot.png")
            )
            val sendIntent: Intent = Intent().apply {
                action = Intent.ACTION_SEND
                setDataAndType(contentUri, "image/png")
                flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                flags = Intent.FLAG_ACTIVITY_NEW_TASK
                putExtra(Intent.EXTRA_SUBJECT, "My W2B stats!")
                val shareMessage = "Here are my W2B stats. What are yours?"
                putExtra(
                    Intent.EXTRA_TEXT,
                    shareMessage + "\n<https://play.google.com/store/apps/details?id=${BuildConfig.APPLICATION_ID}>"
                )
                putExtra(Intent.EXTRA_STREAM, contentUri)
            }
            val shareIntent = Intent.createChooser(sendIntent, "Share Content")
            context.startActivity(shareIntent)
        }

    }) {
        Icon(
            Icons.Filled.Share, "Share Icon Button",
            tint =
            if (!isSystemInDarkTheme()) Color.DarkGray else Color.White,
        )
    }
z
Your coroutine will get cancelled when the scope leaves the composition, assuming you're using rememberCoroutineScope. But I see you're also creating a Handler, which doesn't participate in structured concurrency so all those guarantees go out the window. Why do you need the handler?
☝️ 1
🙏 1
n
Thanks, that was the issue. I did not need the Handler! 😊