Home >Java >javaTutorial >What are the suitable replacements for AsyncTask in Android 11 and how can I migrate my existing AsyncTask code to use them, targeting minSdkVersion 16?

What are the suitable replacements for AsyncTask in Android 11 and how can I migrate my existing AsyncTask code to use them, targeting minSdkVersion 16?

DDD
DDDOriginal
2024-12-15 07:18:14219browse

What are the suitable replacements for AsyncTask in Android 11 and how can I migrate my existing AsyncTask code to use them, targeting minSdkVersion 16?

AsyncTask API deprecated in Android 11: What are the alternatives?

Google has announced that it will deprecate the Android AsyncTask API in Android 11 and recommends using java.util.concurrent instead. You can view the commit information here:

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

If you are maintaining an older codebase that uses asynchronous tasks in Android, it is likely that you will need to change it in the future. My question is, how can I properly replace the code snippet shown below with java.util.concurrent. It is a static inner class of Activity. I'm looking for a solution that works in 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) ;
        }     


    }

Alternative:

You can directly use Executors from the java.util.concurrent package.

I also searched for some information online and found a solution in the following article: Android Async API is deprecated.

Unfortunately the article is written in Kotlin but after some effort I have converted it to Java. So, below is the solution.

ExecutorService executor = Executors.newSingleThreadExecutor();
Handler handler = new Handler(Looper.getMainLooper());

executor.execute(new Runnable() {
    @Override
    public void run() {

        //Background work here

        handler.post(new Runnable() {
            @Override
            public void run() {
                //UI Thread work here
            }
        });
    }
});

Isn’t it very simple? If you use Java 8 in your project, you can simplify it even further.

ExecutorService executor = Executors.newSingleThreadExecutor();
Handler handler = new Handler(Looper.getMainLooper());

executor.execute(() -> {
    //Background work here
    handler.post(() -> {
        //UI Thread work here
    });
});

Still, it doesn't beat kotlin in terms of concise code, but it's better than previous java versions.

Hope this helps. Thanks you!

The above is the detailed content of What are the suitable replacements for AsyncTask in Android 11 and how can I migrate my existing AsyncTask code to use them, targeting minSdkVersion 16?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn