使用 Kotlin 协程处理线程
代码崩溃的原因是因为 Bitmap
试图在 Main Thread
上创建,这是不允许的,因为它可能会导致 Android Not Responding (ANR) 错误。
所用概念
- Kotlin 协程。请参阅此文档了解详情。
- 下面使用了 Loading, Content, Error (LCE) 模式。如有兴趣,您可以在此演示和视频中了解更多信息。
- 使用了 LiveData 返回数据。我将我的最爱 LiveData 资源编译在这些笔记中。
- 在奖励代码中,
toBitmap()
是一个 Kotlin 扩展函数,需要将该库添加到应用依赖项中。
实现
代码
1. 在与 Main Thread
不同的线程中创建 Bitmap
。
在本示例中,使用 Kotlin 协程 将函数执行在线程 Dispatchers.IO
中,该线程用于基于 CPU 的操作。该函数加上了前缀 suspend
,这是协程语法。
奖励 - 在创建 Bitmap
后,还将其压缩成一个 ByteArray
,以便稍后通过 Intent
传递,详细信息请参阅此完整示例。
Repository.kt
suspend fun bitmapToByteArray(url: String) = withContext(Dispatchers.IO) {
MutableLiveData<Lce<ContentResult.ContentBitmap>>().apply {
postValue(Lce.Loading())
postValue(Lce.Content(ContentResult.ContentBitmap(
ByteArrayOutputStream().apply {
try {
BitmapFactory.decodeStream(URL(url).openConnection().apply {
doInput = true
connect()
}.getInputStream())
} catch (e: IOException) {
postValue(Lce.Error(ContentResult.ContentBitmap(ByteArray(0), "bitmapToByteArray error or null - ${e.localizedMessage}")))
null
}?.compress(CompressFormat.JPEG, BITMAP_COMPRESSION_QUALITY, this)
}.toByteArray(), "")))
}
}
ViewModel.kt
private fun bitmapToByteArray(url: String) = liveData {
emitSource(switchMap(repository.bitmapToByteArray(url)) { lce ->
when (lce) {
is Lce.Loading -> liveData {}
is Lce.Content -> liveData {
emit(Event(ContentResult.ContentBitmap(lce.packet.image, lce.packet.errorMessage)))
}
is Lce.Error -> liveData {
Crashlytics.log(Log.WARN, LOG_TAG,
"bitmapToByteArray error or null - ${lce.packet.errorMessage}")
}
}
})
}
奖励 - 将 ByteArray
转换为 Bitmap
。
Utils.kt
fun ByteArray.byteArrayToBitmap(context: Context) =
run {
BitmapFactory.decodeByteArray(this, BITMAP_OFFSET, size).run {
if (this != null) this
else AppCompatResources.getDrawable(context, ic_coinverse_48dp)?.toBitmap()
}
}
<uses-permission android:name="android.permission.INTERNET" />
- Tyeomans