使用Kotlin的Android AsyncTask

本文详细介绍了如何在Android应用中使用Kotlin实现AsyncTask,包括AsyncTask的概念、生命周期方法、防止内存泄漏的方法,以及一个具体的Kotlin AsyncTask项目结构示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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<Params, Progress, Result>

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"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnDoAsync"
        android:gravity="center"
        android:text="Value if returned from the AsyncTask, will be displayed here" />

    <Button
        android:id="@+id/btnDoAsync"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="16dp"
        android:text="START ASYNC TASK" />


    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btnDoAsync"
        android:visibility="gone"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

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

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<Int, String, String?>() {

            private var resp: String? = null
            private val activityReference: WeakReference<MainActivity> = 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.

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值