在Android 11中,AsyncTask API已被弃用。取而代之的是使用更现代的并发库如java.util.concurrent
或Kotlin协程来处理异步任务。下面是使用java.util.concurrent
库和Kotlin协程的代码示例来替代AsyncTask API。
java.util.concurrent
库:import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class MyTask {
private Executor executor = Executors.newSingleThreadExecutor();
public void startTask() {
executor.execute(new Runnable() {
@Override
public void run() {
// 在后台执行耗时任务
// ...
// 更新UI,请使用runOnUiThread方法
}
});
}
}
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class MyTask {
private val coroutineScope = CoroutineScope(Dispatchers.Main)
fun startTask() {
coroutineScope.launch {
// 在后台执行耗时任务
// ...
// 更新UI
}
}
}
注意:在使用上述替代方案时,需要在后台线程执行耗时任务,并在需要更新UI时切回主线程。对于UI更新,可以使用runOnUiThread
方法(对于java.util.concurrent
库)或Dispatchers.Main
调度器(对于Kotlin协程)来在主线程上运行相应的代码。