首页 > 解决方案 > “不适当的阻塞方法调用” - 如何在 Android Studio 上处理此警告

问题描述

我已经编写了这个代码片段来将图像文件从 firebase 存储下载到本地存储。

contentResolver.openOutputStream(uri)?.use { ops ->   // *
    Firebase.storage.getReferenceFromUrl(model.mediaUrl).stream.await().stream.use { ips ->
        val buffer = ByteArray(1024)
        while (true) {
            val bytes = ips.read(buffer)   // *
            if (bytes == -1)
                break
            ops.write(buffer, 0, bytes)   // *
        }
    }
}

在标记的行中,android studio 向我Inappropriate blocking method call发出警告,突出显示 openOutputStream()、read() 和 write() 函数。我已经运行了几次代码并且它运行正常。整个代码片段在一个挂起函数中,从 IO CoroutineScope 调用。
有人请告诉我此警告的实际原因和解决方案。

编辑此代码在以下上下文中调用。

fun someFunc() {
    lifecycleScope.launch(IO) {
        val uri = getUri(model)
        ...
    }
    ...
}
...
suspend fun getUri(model: Message): Uri {
    ... // Retrive the image file using mediastore.
    if ( imageNotFound ) return downloadImage(model)
    else return foundUri
}
suspend fun downloadImage(model: Message): Uri {
    ... // Create contentvalues for new image.
    val uri = contentResolver.insert(collectionUri, values)!!
    // Above mentioned code snippet is here.
    return uri
}

标签: androidkotlininputstreamkotlin-coroutinesoutputstream

解决方案


一个正确组合的挂起函数永远不会阻塞。它不应该依赖于从特定的调度程序调用,而是应该在适当的调度程序中显式地包装阻塞代码。

因此,调用阻塞代码的挂起函数部分应该包含在withContext(Dispatchers.IO){}. 然后调用它的协程甚至不需要指定调度程序。这使得调用函数和更新 UI 非常方便,lifecycleScope无需担心调度程序。

例子:

suspend fun foo(file: File) {
    val lines: List<String> = withContext(Dispatchers.iO) {
        file.readLines()
    }
    println("The file has ${lines.size} lines.")
}

推荐阅读