当前位置: 首页 > 知识库问答 >
问题:

不推荐的用于导入Android.os.AsyncTask的代码[重复]

卓正业
2023-03-14
import android.os.AsyncTask
import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import org.json.JSONObject
import java.net.URL
import java.text.SimpleDateFormat
import java.util.*

class MainActivity : AppCompatActivity() {

    val LAT: String = "1.4854081"
    val LON: String = "14.6618699"
    val API: String = "API FROM OPEN WEATHER REMOVED"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        weatherTask().execute()

    }

    inner class weatherTask() : AsyncTask<String, Void, String>() {
        override fun onPreExecute() {
            super.onPreExecute()
            /* Showing the ProgressBar, Making the main design GONE */
            findViewById<ProgressBar>(R.id.loader).visibility = View.VISIBLE
            findViewById<RelativeLayout>(R.id.mainContainer).visibility = View.GONE
            findViewById<TextView>(R.id.errorText).visibility = View.GONE
        }

        override fun doInBackground(vararg params: String?): String? {
            var response:String?
            try{
                response = URL("https://api.openweathermap.org/data/2.5/weather?lat=$LAT&lon=$LON&units=metric&appid=$API").readText(
                    Charsets.UTF_8
                )
            }catch (e: Exception){
                response = null
            }
            return response
        }

        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            try {
                /* Extracting JSON returns from the API */
                val jsonObj = JSONObject(result)
                val main = jsonObj.getJSONObject("main")
                val sys = jsonObj.getJSONObject("sys")
                val wind = jsonObj.getJSONObject("wind")
                val weather = jsonObj.getJSONArray("weather").getJSONObject(0)

                val updatedAt:Long = jsonObj.getLong("dt")
                val updatedAtText = "Updated at: "+ SimpleDateFormat("dd/MM/yyyy hh:mm a", Locale.ENGLISH).format(Date(updatedAt*1000))
                val temp = main.getString("temp")+"°C"
                val tempMin = "Min Temp: " + main.getString("temp_min")+"°C"
                val tempMax = "Max Temp: " + main.getString("temp_max")+"°C"
                val pressure = main.getString("pressure")
                val humidity = main.getString("humidity")

                val sunrise:Long = sys.getLong("sunrise")
                val sunset:Long = sys.getLong("sunset")
                val windSpeed = wind.getString("speed")
                val weatherDescription = weather.getString("description")

                val address = jsonObj.getString("name")+", "+sys.getString("country")

                /* Populating extracted data into our views */
                findViewById<TextView>(R.id.address).text = address
                findViewById<TextView>(R.id.updated_at).text =  updatedAtText
                findViewById<TextView>(R.id.status).text = weatherDescription.capitalize()
                findViewById<TextView>(R.id.temp).text = temp
                findViewById<TextView>(R.id.temp_min).text = tempMin
                findViewById<TextView>(R.id.temp_max).text = tempMax
                findViewById<TextView>(R.id.sunrise).text = SimpleDateFormat("hh:mm a", Locale.ENGLISH).format(Date(sunrise*1000))
                findViewById<TextView>(R.id.sunset).text = SimpleDateFormat("hh:mm a", Locale.ENGLISH).format(Date(sunset*1000))
                findViewById<TextView>(R.id.wind).text = windSpeed
                findViewById<TextView>(R.id.pressure).text = pressure
                findViewById<TextView>(R.id.humidity).text = humidity

                /* Views populated, Hiding the loader, Showing the main design */
                findViewById<ProgressBar>(R.id.loader).visibility = View.GONE
                findViewById<RelativeLayout>(R.id.mainContainer).visibility = View.VISIBLE

            } catch (e: Exception) {
                findViewById<ProgressBar>(R.id.loader).visibility = View.GONE
                findViewById<TextView>(R.id.errorText).visibility = View.VISIBLE
            }

        }
    }
}

 

共有1个答案

穆俊杰
2023-03-14

您可以使用Kotlin coroutines实现类似于AsyncTask的内容:

class AsyncTaskViewModel : ViewModel() {
    
    fun <R> execute(
            onPreExecute: () -> Unit,
            doInBackground: () -> R,
            onPostExecute: (R) -> Unit
    ) = viewModelScope.launch {
        onPreExecute()
        val result = withContext(Dispatchers.IO) { // runs in background thread without blocking the Main Thread
            doInBackground()
        }
        onPostExecute(result)
    }
}

活动中检索AsynctaskViewModel

val vm: AsyncTaskViewModel by lazy { ViewModelProvider(this)[AsyncTaskViewModel::class.java] }

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    vm.execute(onPreExecute = {
        //...
    }, doInBackground = {
        //...
        "Response" // value to return
    }, onPostExecute = {
        // ... here "it" contains data returned from "doInBackground"
    })
}

如果您不想使用viewmodel,只需在coroutinescope上创建一个扩展函数,并从activity:

// extension function:

fun <R> CoroutineScope.executeAsyncTask(
        onPreExecute: () -> Unit,
        doInBackground: () -> R,
        onPostExecute: (R) -> Unit
) = launch {
    onPreExecute()
    val result = withContext(Dispatchers.IO) { // runs in background thread without blocking the Main Thread
        doInBackground()
    }
    onPostExecute(result)
}


// Call it from Activity: 

lifecycleScope.executeAsyncTask(onPreExecute = {
    // ...
}, doInBackground = {
    //...
    "Response" // value to return
}, onPostExecute = {
    // ... here "it" contains data returned from "doInBackground"
})
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$LIFECYCLE_VERSION" // for viewModelScope
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$LIFECYCLE_VERSION" // for lifecycleScope
 类似资料:
  • 你能帮助采用代码iOS7吗?我有代码: 但是Xcode说size的字体:字体size的字体:字体和线型断开模式在iOS7中已弃用。 请帮我更新这一行代码。

  • 问题内容: 在Java中,如果导入不推荐使用的类: 您收到此警告: 有没有办法抑制这种警告? 问题答案: 在您的类或方法上使用此注释:

  • 介绍 本文介绍的四种代码复用模式都是最佳实践,推荐大家在编程的过程中使用。 模式1:原型继承 原型继承是让父对象作为子对象的原型,从而达到继承的目的: function object(o) { function F() { } F.prototype = o; return new F(); } // 要继承的父对象 var parent = { nam

  • 问题内容: 我正在寻找解析URL以获得Java中querystring参数的集合。为了清楚起见,我需要解析给定的URL(或URL对象的字符串值),而不是Servlet请求中的URL。 似乎该方法将是显而易见的选择,但已弃用。 是否有我缺少的替代方法,或者只是不推荐使用而没有等效的替换/增强功能? 问题答案: 嗯,正如您提到的,URL不是来自servlet请求,正确的答案通常 取决于它 。 网址的查

  • 我只是更新我的服务器。今天显示了一个错误 deprecated:mysql_query():mysql扩展是不推荐的,并将在>future中删除:使用mysqli或PDO代替C:\wamp\www\work\db\dbfields-copy.php中的第33行 我创建了2列(name&address),需要插入var的值($name&$address)。

  • 这是什么意思,我如何消除信息?