如何解决通过Kotlin协程将JSON文件下载到Android应用
我试图将doInBackground从AsyncTask重写为Kotlin协程。好消息是我不会再犯任何错误,不好的一个-不起作用。老实说,我不确定是否可以这种形式使用,我正在寻找信息,如果我选择了正确的方向。我应该用setStringOnMainThread()中的Context(Main)填充吗?感谢您的建议。
package com.whayway.flickapp
import android.util.Log
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.withContext
import java.io.IOException
import java.net.MalformedURLException
import java.net.URL
private var downloadStatus = DownloadStatus.IDLE
private const val TAG = "GetRawData"
enum class DownloadStatus {
OK,IDLE,NOT_INITIALISED,FAILED_OR_EMPTY,PERMISSIONS_ERROR,ERROR
}
open class GetRawData {
private suspend fun setStringOnMainThread(input: String) {
logThread("setStringOnMainThread")
withContext(Main) {
}
}
suspend fun downloadData(vararg params: String?): String {
logThread("doInBackground")
if (params[0] == null) {
downloadStatus = DownloadStatus.NOT_INITIALISED
setStringOnMainThread("No URL specified\"")
}
try {
downloadStatus = DownloadStatus.OK
return setStringOnMainThread(URL(params[0]).readText()).toString()
} catch (e: Exception) {
val errorMessage = when (e) {
is MalformedURLException -> {
downloadStatus = DownloadStatus.NOT_INITIALISED
"doInBackground: Invalid URL ${e.message}"
}
is IOException -> {
downloadStatus = DownloadStatus.FAILED_OR_EMPTY
"doInBackground: IO Exception reading data: ${e.message}"
}
is SecurityException -> {
downloadStatus = DownloadStatus.PERMISSIONS_ERROR
"doInBackground: Security exception: Needs permission? ${e.message}"
}
else -> {
downloadStatus = DownloadStatus.ERROR
"Unknown error: ${e.message}"
}
}
Log.e(TAG,errorMessage)
return setStringOnMainThread(errorMessage).toString()
}
}
private fun logThread(methodName: String){
println("debug: ${methodName}: ${Thread.currentThread().name}")
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。