As AsyncTask is no longer supported in Android 11, Google recommends developers utilize java.util.concurrent
instead. Here’s an example of the previous usage of AsyncTask:
/**
* @deprecated Replace with standard <code>java.util.concurrent</code> or
* <code>Kotlin concurrency utilities</code>.
*/
@Deprecated
public abstract class AsyncTask<Params, Progress, Result> {
}
If you are responsible for an older Android codebase that employs asynchronous processes, what would be a suitable replacement for the following AsyncTask example using java.util.concurrent
? This static inner class is part of an Activity and needs to be compatible with minSdkVersion 16
.
private static class BackgroundProcess extends AsyncTask<String, Void, MyData> {
private static final String TAG = MyActivity.BackgroundProcess.class.getSimpleName();
private WeakReference<MyActivity> activityWeakRef;
BackgroundProcess(MyActivity activity) {
activityWeakRef = new WeakReference<>(activity);
}
@Override
protected MyData doInBackground(String... inputs) {
// Perform lengthy operation here
}
@Override
protected void onPostExecute(MyData result) {
MyActivity activity = activityWeakRef.get();
activity.loadingIndicator.setVisibility(View.GONE);
updateUI(activity, result);
}
}