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.
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();
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?