Sobes.tech
Middle

How to run asynchronous operations in pure Android?

sobes.tech AI

Answer from AI

Several methods can be used:

  • Thread: Creating a new thread to perform a task. Simple, but managing the lifecycle and passing data back to the main thread requires additional logic (Handler, runOnUiThread).

    new Thread(new Runnable() {
        @Override
        public void run() {
            // Perform asynchronous operation
            // Update UI via runOnUiThread or Handler
        }
    }).start();
    
  • AsyncTask: Deprecated but simple class for executing background operations and updating UI. Provides methods onPreExecute, doInBackground, onProgressUpdate, onPostExecute.

    private static class MyAsyncTask extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... voids) {
            // Perform asynchronous operation
            return "Result";
        }
    
        @Override
        protected void onPostExecute(String result) {
            // Update UI on the main thread
        }
    }
    
    // To start: new MyAsyncTask().execute();
    
  • Handler and Looper: More flexible mechanism for sending and processing messages and tasks between threads. Handler is associated with the Looper of the thread it was created in.

    Handler handler = new Handler(Looper.getMainLooper()); // For main thread
    
    handler.post(new Runnable() {
        @Override
        public void run() {
            // Perform task on the main thread after asynchronous operation
        }
    });
    
  • ExecutorService and Callable/Runnable: Standard Java mechanisms for managing thread pools. Allow more efficient resource use and task management.

    ExecutorService executor = Executors.newSingleThreadExecutor(); // Or other executor type
    
    executor.submit(new Runnable() {
        @Override
        public void run() {
            // Perform asynchronous operation
        }
    });
    
    // Or submit(Callable) to get a result
    
  • Coroutine (with Kotlin): More modern and convenient way to manage asynchronous operations in Kotlin. Allows writing asynchronous code in an imperative style. Requires adding the appropriate dependencies.

    import kotlinx.coroutines.*
    
    GlobalScope.launch(Dispatchers.IO) {
        // Perform asynchronous operation in background thread
        withContext(Dispatchers.Main) {
            // Update UI on the main thread
        }
    }
    
How to run asynchronous operations in pure Android… - sobes.tech