Examples of Handler usage in production apps?

In Android development, the Handler class is commonly used for managing communication between threads, allowing you to send and process Message and Runnable objects associated with a thread’s MessageQueue. Below are some practical examples of using Handlers in production apps.

// Example of using Handler to post a delayed message public class MainActivity extends AppCompatActivity { private Handler handler = new Handler(Looper.getMainLooper()); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); handler.postDelayed(new Runnable() { @Override public void run() { // Code to execute after delay Toast.makeText(MainActivity.this, "Delayed Action!", Toast.LENGTH_SHORT).show(); } }, 3000); // 3000 milliseconds delay } }

In this example, a Handler is used to display a Toast message after a 3-second delay. This technique can be useful for situations where you need to wait for a specific period before executing certain actions, like showing tips or initiating processes.

// Example using Handler to update UI from a background thread public class MyBackgroundTask { private Handler handler; public MyBackgroundTask(Handler handler) { this.handler = handler; } public void doBackgroundTask() { new Thread(new Runnable() { @Override public void run() { // Simulate long running task try { Thread.sleep(5000); // 5 seconds } catch (InterruptedException e) { e.printStackTrace(); } // Update UI after task completion handler.post(new Runnable() { @Override public void run() { // Code to update the UI // For example, update a TextView myTextView.setText("Task Complete!"); } }); } }).start(); } }

This example illustrates how to use a Handler to update the UI after completing a lengthy background task. Since UI updates must be performed on the main thread, the Handler facilitates this communication smoothly.


Android Handler Message Runnable Thread UI Updates Background Task