通过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 (将#修改为@)