Junior — Middle
How to determine the correct Looper to use with Handler for data exchange between background and main threads?
sobes.tech AI
Answer from AI
In Android, a Handler is associated with a Looper, which manages the message queue for a specific thread. To communicate between a background thread and the main thread, you need to use the appropriate Looper:
- For the main (UI) thread, use
Looper.getMainLooper(). - For a background thread, you can create your own
LooperusingHandlerThread.
Example:
// To send messages to the main thread
Handler mainHandler = new Handler(Looper.getMainLooper());
// Create a HandlerThread for the background thread
HandlerThread handlerThread = new HandlerThread("MyBackgroundThread");
handlerThread.start();
Handler backgroundHandler = new Handler(handlerThread.getLooper());
// Use mainHandler.post(...) to update UI from the background thread
// Use backgroundHandler.post(...) to execute tasks in the background
Thus, the correct Looper is chosen based on the thread where the code should run: for UI — Looper.getMainLooper(), for background — HandlerThread.getLooper().