Android 11中不推荐使用AsyncTask API。有什么替代方案吗?

The AsyncTask API is deprecated in Android 11. What are the alternatives?(Android 11中不推荐使用AsyncTask API。有什么替代方案吗?)

本文介绍了Android 11中不推荐使用AsyncTask API。有什么替代方案吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Google在Android 11中弃用Android AsyncTask API,建议使用java.util.concurrent。您可以签出提交here

 *
 * @deprecated Use the standard <code>java.util.concurrent</code> or
 *   <a href="https://developer.android.com/topic/libraries/architecture/coroutines">
 *   Kotlin concurrency utilities</a> instead.
 */
@Deprecated
public abstract class AsyncTask<Params, Progress, Result> {

如果您在Android中使用异步任务维护较旧的代码库,则很可能将来必须更改它。我的问题是,使用java.util.concurrent应该如何正确替换下面显示的代码片段。它是一个活动的静电内部类。我正在寻找可以与minSdkVersion 16

一起使用的软件
private static class LongRunningTask extends AsyncTask<String, Void, MyPojo> {
        private static final String TAG = MyActivity.LongRunningTask.class.getSimpleName();
        private WeakReference<MyActivity> activityReference;

        LongRunningTask(MyActivity context) {
            activityReference = new WeakReference<>(context);
        }

        @Override
        protected MyPojo doInBackground(String... params) {
            // Some long running task
            
        }

        @Override
        protected void onPostExecute(MyPojo data) {

            MyActivity activity = activityReference.get();
            activity.progressBar.setVisibility(View.GONE);
            populateData(activity, data) ;
        }     


    }

推荐答案

private WeakReference<MyActivity> activityReference;

幸好它已被弃用,because the WeakReference<Context> was always a hack, and not a proper solution。

现在,用户将有机会清理其代码。


AsyncTask<String, Void, MyPojo> 

基于此代码,实际上不需要Progress,有一个String输入+MyPojo输出。

无需使用任何AsyncTask,这实际上很容易实现。

public class TaskRunner {
    private final Executor executor = Executors.newSingleThreadExecutor(); // change according to your requirements
    private final Handler handler = new Handler(Looper.getMainLooper());

    public interface Callback<R> {
        void onComplete(R result);
    }

    public <R> void executeAsync(Callable<R> callable, Callback<R> callback) {
        executor.execute(() -> {
            final R result = callable.call();
            handler.post(() -> {
                callback.onComplete(result);
            });
        });
    }
}

如何传入字符串?如下所示:

class LongRunningTask implements Callable<MyPojo> {
    private final String input;

    public LongRunningTask(String input) {
        this.input = input;
    }

    @Override
    public MyPojo call() {
        // Some long running task
        return myPojo;
    }
}

// in ViewModel
taskRunner.executeAsync(new LongRunningTask(input), (data) -> {
    // MyActivity activity = activityReference.get();
    // activity.progressBar.setVisibility(View.GONE);
    // populateData(activity, data) ;

    loadingLiveData.setValue(false);
    dataLiveData.setValue(data);
});

// in Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main_activity);

    viewModel = ViewModelProviders.of(this).get(MyViewModel.class);
    viewModel.loadingLiveData.observe(this, (loading) -> {
        if(loading) {
            progressBar.setVisibility(View.VISIBLE);
        } else {
            progressBar.setVisibility(View.GONE);
        }
    });

    viewModel.dataLiveData.observe(this, (data) -> {
        populateData(data);
    }); 
}

本例使用的单线程池非常适合DB写入(或序列化的网络请求),但是如果您想要用于DB读取或多个请求,您可以考虑以下执行器配置:

private static final Executor THREAD_POOL_EXECUTOR =
        new ThreadPoolExecutor(5, 128, 1,
                TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

这篇关于Android 11中不推荐使用AsyncTask API。有什么替代方案吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Android 11中不推荐使用AsyncTask API。有什么替代方案吗?

基础教程推荐