In this tutorial, we’ll learn and implement AsyncTask using Kotlin in our Android Application.

在本教程中,我们将在Android应用程序中使用Kotlin学习和实现AsyncTask。

什么是Android AsyncTask? (What is Android 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:

异步任务的三个类型参数是:

  1. Params: The type of the parameters sent to the AsyncTask.

    Params :发送到AsyncTask的参数的类型。
  2. Progress: The type of the progress units published during the background computation.

    Progress :在后台计算期间发布的进度单位的类型。
  3. Result: The type of the result of the background computation.

    Result :后台计算Result的类型。

AsyncTask方法 (AsyncTask Methods)

AsyncTask has four methods that are triggered at different times during the life cycle of async task execution.

AsyncTask具有四种方法,这些方法在异步任务执行的生命周期中的不同时间触发。

  1. 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相关的任务。
  2. doInBackground: The background execution code goes in this method. We cannot call the Activity’s UI instances in this method.

    doInBackground :后台执行代码使用此方法。 我们无法使用此方法调用Activity的UI实例。
  3. 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线程当前进度,则可以使用此方法。
  4. 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更改,例如使用返回的值更新视图。

如何在Kotlin中创建AsyncTask? (How to Create AsyncTask in Kotlin?)

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是在伴随对象中定义的。

为什么非静态AsyncTask会导致内存泄漏? (Why non-static AsyncTask can cause memory leaks?)

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

Android AsyncTask Kotlin项目结构 (Android AsyncTask Kotlin Project Structure)

1. XML布局代码 (1. XML Layout Code)

The code for the activity_main.xml layout file is given below:

下面给出了activity_main.xml布局文件的代码:

<?xml version="1.0" encoding="utf-8"?>        

2. Kotlin活动类代码 (2. Kotlin Activity Class Code)

The MainActivity.kt Kotlin Activity class is given below.

MainActivity.kt Kotlin活动类如下所示。

package net.androidly.androidlyasynctaskimport android.support.v7.app.AppCompatActivityimport android.os.Bundleimport kotlinx.android.synthetic.main.activity_main.*import android.os.AsyncTaskimport android.view.Viewimport android.widget.Toastimport java.lang.ref.WeakReferenceclass 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可空类型返回的字符串。

3. AsyncTask应用程序输出 (3. AsyncTask App Output)

The output of the above application in action is given below.

下面给出了上面应用程序的输出。

AndroidlyAsyncTask AndroidlyAsyncTask

翻译自: https://www.journaldev.com/245/android-asynctask-kotlin

更多相关文章

  1. 浅谈Java中Collections.sort对List排序的两种方法
  2. 箭头函数的基础使用
  3. NPM 和webpack 的基础使用
  4. Python list sort方法的具体使用
  5. 【阿里云镜像】使用阿里巴巴DNS镜像源——DNS配置教程
  6. python list.sort()根据多个关键字排序的方法实现
  7. android上一些方法的区别和用法的注意事项
  8. android 使用html5作布局文件: webview跟javascript交互
  9. android实现字体闪烁动画的方法

随机推荐

  1. android aidl iBinder理解
  2. [置顶] Android之ContextMenu的使用方法
  3. Android之网络通信·Web通讯
  4. android Q open failed: EACCES (Permiss
  5. [Android] 开发资料收集:多媒体开发
  6. android 动画详解(一)
  7. 车载多媒体Android开发平台学习心得
  8. Android记录12--控制屏幕常亮不锁屏
  9. android视频录制、另一部手机实时观看方
  10. android部分控件属性摘抄