Browse Source

wizard: Make sure bitmaps are recycled properly

Co-authored-by: septs <github@septs.pw>
Peter Cai 11 months ago
parent
commit
d3df70501a

+ 6 - 9
app-common/src/main/java/im/angry/openeuicc/ui/wizard/DownloadWizardMethodSelectFragment.kt

@@ -44,17 +44,14 @@ class DownloadWizardMethodSelectFragment : DownloadWizardActivity.DownloadWizard
 
 
             lifecycleScope.launch(Dispatchers.IO) {
             lifecycleScope.launch(Dispatchers.IO) {
                 runCatching {
                 runCatching {
-                    requireContext().contentResolver.openInputStream(result)?.let { input ->
-                        val bmp = BitmapFactory.decodeStream(input)
-                        input.close()
-
-                        decodeQrFromBitmap(bmp)?.let {
-                            withContext(Dispatchers.Main) {
-                                processLpaString(it)
+                    requireContext().contentResolver.openInputStream(result)?.use { input ->
+                        BitmapFactory.decodeStream(input).use { bmp ->
+                            decodeQrFromBitmap(bmp)?.let {
+                                withContext(Dispatchers.Main) {
+                                    processLpaString(it)
+                                }
                             }
                             }
                         }
                         }
-
-                        bmp.recycle()
                     }
                     }
                 }
                 }
             }
             }

+ 7 - 0
app-common/src/main/java/im/angry/openeuicc/util/Utils.kt

@@ -86,6 +86,13 @@ suspend fun connectSEService(context: Context): SEService = suspendCoroutine { c
     }
     }
 }
 }
 
 
+inline fun <T> Bitmap.use(f: (Bitmap) -> T): T =
+    try {
+        f(this)
+    } finally {
+        recycle()
+    }
+
 fun decodeQrFromBitmap(bmp: Bitmap): String? =
 fun decodeQrFromBitmap(bmp: Bitmap): String? =
      runCatching {
      runCatching {
         val pixels = IntArray(bmp.width * bmp.height)
         val pixels = IntArray(bmp.width * bmp.height)