How to integrate Handler with other Android components?

In Android development, the Handler class is a powerful tool used to manage the message queue of a thread. It allows you to send and process `Message` and `Runnable` objects associated with a thread's `MessageQueue`. Integrating a Handler with various Android components such as Activities, Fragments, and Services can enhance responsiveness and manage UI updates smoothly.

Example of Integrating Handler with an Activity

Below is an example showing how to use a Handler to update the UI from a background thread in an Activity.

// MainActivity.java public class MainActivity extends AppCompatActivity { private Handler handler; private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); handler = new Handler(Looper.getMainLooper()); new Thread(new Runnable() { @Override public void run() { // Simulating a long-running task try { Thread.sleep(2000); // Sleep for 2 seconds } catch (InterruptedException e) { e.printStackTrace(); } // Sending a message to be handled on the UI thread handler.post(new Runnable() { @Override public void run() { textView.setText("Task Completed!"); } }); } }).start(); } }

Handler integration Android components Android development UI thread management Activity example.