Skip to content

Instantly share code, notes, and snippets.

@chayanforyou
Last active February 2, 2025 16:37
Show Gist options
  • Save chayanforyou/75654048b42162d4baed48513be86e6f to your computer and use it in GitHub Desktop.
Save chayanforyou/75654048b42162d4baed48513be86e6f to your computer and use it in GitHub Desktop.
Android AsyncTask is Deprecated: Here’s another way

According to the Android documentation AsyncTask was deprecated in API level 30 and it is suggested to use the standard java.util.concurrent or Kotlin concurrency utilities instead.

AsyncTasks.java

public abstract class AsyncTasks<Params, Result> {

    private final ExecutorService executors;

    public AsyncTasks() {
        this.executors = Executors.newSingleThreadExecutor();
    }

    @SafeVarargs
    private final void startBackground(Params... params) {
        onPreExecute();
        executors.execute(() -> {
            Result result = doInBackground(params);
            new Handler(Looper.getMainLooper()).post(() -> onPostExecute(result));
        });
    }

    @SafeVarargs
    public final void execute(Params... params) {
        startBackground(params);
    }

    public void shutdown() {
        executors.shutdown();
    }

    public boolean isShutdown() {
        return executors.isShutdown();
    }

    @SuppressWarnings("unchecked")
    protected abstract Result doInBackground(Params... params);

    protected void onPreExecute() {}

    protected void onPostExecute(Result result) {}
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

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

        // Simply call to execute task
        new MyTask().execute();
    }

    /**
     * Sub-class of AsyncTask
     */
    private class MyTask extends AsyncTasks<Void, String> {

        @Override
        protected void onPreExecute() {
            // Before execution
        }

        @Override
        protected String doInBackground(Void... args) {
            // Background task here
            return "TASK_COMPLETE";
        }

        @Override
        protected void onPostExecute(String result) {
            // UI task here
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment