Tech Blog

Android, Programming

Replacement of Deprecated AsyncTask in Android

By Jignesh Mundhava2 min read
← Back to blog

AsyncTask is used to perform time talking operations in android, but it’s marked as deprecated from android 11. 

There are many alternatives are available for replacing an AsyncTask, one of the replacements is ExecutorService.

AsyncTask Code:

public class LoadAppsAsyncTask extends AsyncTask <Void, Void, Void> {

    @Override
    protected Void onPreExecute() {
        // before start background execution
    }

    @Override
    protected Void doInBackground(Void...params) {
        // perform background load app task and return a result based on need
    }

    @Override
    protected void onPostExecute(Void result) {}

}

Above code snippet is general example of AsyncTask, for replace deprecated Async class, first create one Generic Class which is used to replace AsyncTask.

Generic Class for Async operations:

public abstract class AsyncTaskExecutorService < Params, Progress, Result > {

    private ExecutorService executor;
 private Handler handler;

    protected AsyncTaskExecutorService() {
        executor = Executors.newSingleThreadExecutor(r - > {
            Thread t = new Thread(r);
            t.setDaemon(true);
            return t;
        });

    }

    public ExecutorService getExecutor() {
        return executor;
    }

    public Handler getHandler() {
        if (handler == null) {
            synchronized(AsyncTaskExecutorService.class) {
                handler = new Handler(Looper.getMainLooper());
            }
        }
        return handler;
    }

    protected void onPreExecute() {
        // Override this method whereever you want to perform task before background execution get started 
    }

    protected abstract Result doInBackground(Params params);

    protected abstract void onPostExecute(Result result);

    protected void onProgressUpdate(@NotNull Progress value) {
        // Override this method whereever you want update a progress result
    }

    // used for push progress resport to UI
    public void publishProgress(@NotNull Progress value) {
        getHandler().post(() - > onProgressUpdate(value));
    }

    public void execute() {
        execute(null);
    }

    public void execute(Params params) {
        getHandler().post(() - > {
            onPreExecute();
            executor.execute(() - > {
                Result result = doInBackground(params);
                getHandler().post(() - > onPostExecute(result));
   });
        });
    }

    public void shutDown() {
        if (executor != null) {
            executor.shutdownNow();
        }
    }

    public boolean isCancelled() {
        return executor == null || executor.isTerminated() || executor.isShutdown();
    }
}

Finally, Use the above genetic class to remove AysncTask 

public class LoadAppsAsyncTask extends AsyncTaskExecutorService < Void, Void, Void > {

    @Override
    protected Void onPreExecute() {
        // before start background execution
    }

    @Override
    protected Void doInBackground(Void params) {
        // perform background task load app and return a result based on need
    }

    @Override
    protected void onPostExecute(Void result) {}

}

just extend your existing AsyncTask with AsyncTaskExecutorService and modify the default method argument.

Keep reading

You may be interested in

Browse all articles →
How to extract APK file of installed application in Android programmatically
June 6, 20221 min read

How to extract APK file of installed application in Android programmatically

Step 1 : Get the path of the installed application Step 2 : Store the Apk file in required folder

By Sushant Singh RathoreRead More →
CPU Usage Monitoring using Android Profiler
June 3, 20224 min read

CPU Usage Monitoring using Android Profiler

The Android Profiler is nothing but a replacement for Android Monitor tools in Android Studio 3.0 and higher. Android Profiler tools get real-time app data which helps to understand how your app uses CPU, memory, network, and battery resources. How to enable Android Profiler Enable inbuild profiler in android studioView > Tool Windows > Profiler […]

By Jignesh MundhavaRead More →
Disable MAC Randomization in Android 10 and above devices
June 1, 20223 min read

Disable MAC Randomization in Android 10 and above devices

Recently we came across an interesting feature, to set static MAC address for the wifi ssids for Android 10 and above devices.MAC Randomization generates a random MAC address for a wifi ssid for the following conditions mentioned below :- When connecting with that particular network for the first time=- Forget and rejoin the network. in […]

By Kumar gauravRead More →