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.