The android.os.Handler class is used to send messages and code to be executed on a different thread or process. It maintains a message queue and dispatches messages to the corresponding thread or process. One of the methods of the Handler class is sendEmptyMessage(int what), which sends an empty message with the specified "what" value.
Example 1: Suppose we have a thread that is responsible for performing some heavy tasks, such as file processing or network operations. We want to notify the UI thread when the task has completed. We can create a Handler object in the UI thread and pass it to the worker thread. Whenever the worker thread completes its task, it can call the sendEmptyMessage(int what) method to notify the UI thread. The UI thread can then update the UI accordingly.
Handler handler = new Handler() { @Override public void handleMessage(Message msg) { int what = msg.what; // Update UI code } };
// Worker thread Thread workerThread = new Thread(new Runnable() { @Override public void run() { // Perform heavy task handler.sendEmptyMessage(0); } }); workerThread.start();
Example 2: Suppose we have an activity that displays a countdown timer. When the timer reaches zero, we want to play a sound effect. We can use a Handler object to schedule the sound effect to play after the timer has finished.
Handler handler = new Handler() { @Override public void handleMessage(Message msg) { int what = msg.what; if (what == 0) { // Play sound effect } } };
@Override public void onFinish() { handler.sendEmptyMessage(0); } }; timer.start();
Package library used: android.os
Java Handler.sendEmptyMessage - 30 examples found. These are the top rated real world Java examples of android.os.Handler.sendEmptyMessage extracted from open source projects. You can rate examples to help us improve the quality of examples.