Android AsyncTask已被弃用

如果你对android开发感兴趣,那么我很确定你对android AsyncTask很了解。AsyncTask类帮助我们在后台线程中执行一些代码。

在AsyncTask的帮助下,我们可以在后台线程上执行某些操作,并在UI线程中返回结果。但Android AsyncTask在API级别30中已被弃用。那么,现在的替代方案是什么?

为什么Android AsyncTask不受欢迎?

以下是官方反对它的原因。

AsyncTask旨在实现UI线程的正确和简单使用。然而,最常见的用例是集成到UI中,这会导致上下文泄漏、错过回调或配置更改时崩溃。它在不同版本的平台上也有不一致的行为,从doInBackground中接受异常,并且与直接使用执行器相比没有提供太多的实用性。

异步任务的替代方案

官方推荐的替代方案是Kotlin协程,您必须在项目中使用它来编写异步代码。

但如果你是一名初学者,并且刚刚开始学习android开发,那么不建议直接跳入Kotlin协同程序。所以在这篇文章中,我将向你展示一些不需要依赖的东西。

使用Executors

我们有java.util.concurrent.Executors。如果您不希望使用Kotlin协程,我们可以使用它来代替AsyncTask。但是建议您使用Kotlin协同程序在项目中编写异步代码

val executor = Executors.newSingleThreadExecutor()
val handler = Handler(Looper.getMainLooper())
executor.execute {
    /*
    * Your task will be executed here
    * you can execute anything here that
    * you cannot execute in UI thread
    * for example a network operation
    * This is a background thread and you cannot
    * access view elements here
    *
    * its like doInBackground()
    * */
    handler.post {
        /*
        * You can perform any operation that
        * requires UI Thread here.
        *
        * its like onPostExecute()
        * */
    }
}

你可能感兴趣的:(android,ui,android,studio)