In this tutorial, we’ll learn and implement AsyncTask using Kotlin in our Android Application.
在本教程中,我们将在Android应用程序中使用Kotlin学习和实现AsyncTask。
Android AsyncTask is an abstract class that’s used to perform long operations in the background. We have to extend this class and implement the abstract methods to use async tasks in our app.
Android AsyncTask是一个抽象类,用于在后台执行较长的操作。 我们必须扩展此类并实现抽象方法以在我们的应用程序中使用异步任务。
inner class SomeTask extends AsyncTask
The three type parameters of an asynchronous task are:
异步任务的三个类型参数是:
Params
: The type of the parameters sent to the AsyncTask. Params
:发送到AsyncTask的参数的类型。 Progress
: The type of the progress units published during the background computation. Progress
:在后台计算期间发布的进度单位的类型。 Result
: The type of the result of the background computation. Result
:后台计算Result
的类型。 AsyncTask has four methods that are triggered at different times during the life cycle of async task execution.
AsyncTask具有四种方法,这些方法在异步任务执行的生命周期中的不同时间触发。
PreExecute
: This is invoked in UI thread before the AsyncTask is executed. We can show a ProgressBar or perform any UI related tasks in this method. PreExecute
:在执行AsyncTask之前在UI线程中调用它。 我们可以使用此方法显示一个ProgressBar或执行任何与UI相关的任务。 doInBackground
: The background execution code goes in this method. We cannot call the Activity’s UI instances in this method. doInBackground
:后台执行代码使用此方法。 我们无法使用此方法调用Activity的UI实例。 onProgressUpdate
: This method gets triggered when the publish progress is invoked in the doInBackground method. This method comes handy if you wish to inform UI thread about the current progress. onProgressUpdate
:在doInBackground方法中调用发布进度时,将触发此方法。 如果您希望通知UI线程当前进度,则可以使用此方法。 onPostExecute
: gets triggered after doInBackground is over. The values returned from the doInBackground are received here. We can do the UI changes here such as updating the views with the values returned. onPostExecute
:在doInBackground结束后被触发。 从doInBackground返回的值在此处接收。 我们可以在此处进行UI更改,例如使用返回的值更新视图。 val task = MyAsyncTask(this)
task.execute(10)
The execute method starts the AsyncTask. We can pass anything in the constructor, generally a context is passed.
execute方法启动AsyncTask。 我们可以在构造函数中传递任何内容,通常会传递上下文。
AsyncTasks are defined as inner classes. We have to define them as static to prevent memory leaks.
AsyncTask被定义为内部类。 我们必须将它们定义为静态,以防止内存泄漏。
In Kotlin, companion object is the equivalent of static classes. So AsyncTasks are defined in a companion object.
在Kotlin中, 伴随对象等效于静态类。 因此,AsyncTasks是在伴随对象中定义的。
When non-static, they hold a reference to the Activity. So, if the AsyncTask exists till after the Activity’s lifecycle, it’ll keep a reference of the Activity thereby causing memory leaks.
当为非静态时,它们保存对活动的引用。 因此,如果AsyncTask一直存在到Activity的生命周期之后,它将保留对Activity的引用,从而导致内存泄漏。
Hence companion object
is used where we can store a weak reference of the Activity.
因此,在可以存储活动的弱引用的地方使用了companion object
。
The code for the activity_main.xml layout file is given below:
下面给出了activity_main.xml布局文件的代码:
The MainActivity.kt Kotlin Activity class is given below.
MainActivity.kt Kotlin活动类如下所示。
package net.androidly.androidlyasynctask
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import android.os.AsyncTask
import android.view.View
import android.widget.Toast
import java.lang.ref.WeakReference
class MainActivity : AppCompatActivity() {
var myVariable = 10
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnDoAsync.setOnClickListener {
val task = MyAsyncTask(this)
task.execute(10)
}
}
companion object {
class MyAsyncTask internal constructor(context: MainActivity) : AsyncTask() {
private var resp: String? = null
private val activityReference: WeakReference = WeakReference(context)
override fun onPreExecute() {
val activity = activityReference.get()
if (activity == null || activity.isFinishing) return
activity.progressBar.visibility = View.VISIBLE
}
override fun doInBackground(vararg params: Int?): String? {
publishProgress("Sleeping Started") // Calls onProgressUpdate()
try {
val time = params[0]?.times(1000)
time?.toLong()?.let { Thread.sleep(it / 2) }
publishProgress("Half Time") // Calls onProgressUpdate()
time?.toLong()?.let { Thread.sleep(it / 2) }
publishProgress("Sleeping Over") // Calls onProgressUpdate()
resp = "Android was sleeping for " + params[0] + " seconds"
} catch (e: InterruptedException) {
e.printStackTrace()
resp = e.message
} catch (e: Exception) {
e.printStackTrace()
resp = e.message
}
return resp
}
override fun onPostExecute(result: String?) {
val activity = activityReference.get()
if (activity == null || activity.isFinishing) return
activity.progressBar.visibility = View.GONE
activity.textView.text = result.let { it }
activity.myVariable = 100
}
override fun onProgressUpdate(vararg text: String?) {
val activity = activityReference.get()
if (activity == null || activity.isFinishing) return
Toast.makeText(activity, text.firstOrNull(), Toast.LENGTH_SHORT).show()
}
}
}
}
When we click the button, AsyncTask is launched in the background.
当我们单击按钮时,AsyncTask在后台启动。
We pass an Int value in the AsyncTask that represents the number of seconds.
我们在AsyncTask中传递一个Int值,该值表示秒数。
In the doInBackground
method, we are putting the thread to sleep for the given number of seconds.
在doInBackground
方法中,我们将线程Hibernate指定的秒数。
We are triggering the progressUpdate
with a String that gets displayed in the Toast.
我们正在使用显示在Toast中的String触发progressUpdate
。
In the onPostExecute
method, we are hiding the ProgressBar and setting the TextView to the string returned by unwrapping the Kotlin Nullable Type.
在onPostExecute
方法中,我们将隐藏ProgressBar并将TextView设置为通过解包Kotlin可空类型返回的字符串。
The output of the above application in action is given below.
下面给出了上面应用程序的输出。
翻译自: https://www.journaldev.com/245/android-asynctask-kotlin