Junior — Middle
Is it possible to implement sending a network request using a handler?
sobes.tech AI
Answer from AI
In Android, Handler is used for processing messages and executing code in a specific thread, most often in the UI thread. By itself, Handler is not intended for sending network requests, as network operations should be performed in a background thread to avoid blocking the UI.
However, Handler can be used to organize interaction between threads: for example, launching a network request in a separate thread or via AsyncTask (deprecated approach) or Executor, and then using Handler to send the results back to the UI thread for interface updates.
Example:
Handler handler = new Handler(Looper.getMainLooper());
new Thread(() -> {
// Perform network request in background thread
String result = performNetworkRequest();
// Send result to UI thread
handler.post(() -> {
// Update UI with result
textView.setText(result);
});
}).start();
Thus, Handler does not perform network requests directly, but helps safely transfer data between threads.