How to perform asynchronous operations in pure Android?
sobes.tech AI
Answer from AI
There are several ways:
-
Threads: Creating and managing your own threads.
new Thread(new Runnable() { @Override public void run() { // Perform long operation // ... // Update UI (requires Handler) // handler.post(...) } }).start(); -
Handler and Looper: Used for message exchange between threads, often for updating UI from a background thread.
Handler handler = new Handler(Looper.getMainLooper()); // ... in background thread handler.post(new Runnable() { @Override public void run() { // Update UI } }); -
AsyncTask (deprecated but useful to know): A simple way to perform asynchronous tasks with UI updates. Not recommended for new code.
private class MyAsyncTask extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... voids) { // Perform long operation return "Result"; } @Override protected void onPostExecute(String result) { // Update UI with result } } // ... // new MyAsyncTask().execute(); -
ExecutorService and Future: A more flexible mechanism for managing thread pools.
ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future = executor.submit(new Callable<String>() { @Override public String call() throws Exception { // Perform long operation return "Result"; } }); // Get result (blocking) // String result = future.get(); -
Kotlin Coroutines: A modern approach for asynchronous programming in Kotlin, based on coroutines. Requires adding dependencies.
import kotlinx.coroutines.* // ... in a coroutine scope (e.g., viewModelScope) GlobalScope.launch(Dispatchers.IO) { // Execute in IO background thread // Perform long operation withContext(Dispatchers.Main) { // Switch to main thread for UI update // Update UI } }
The choice of method depends on the complexity of the task, the level of control over threads required, and language preferences (Java/Kotlin). In modern Android development, it is recommended to use Kotlin Coroutines or libraries for asynchronous work, such as RxJava or Flow.