SoFunction
Updated on 2025-04-14

Android Handler Usage Guide

Detailed explanation of the usage of Handler in Android

Handler is an important mechanism used in Android for inter-thread communication, mainly used to send and process messages between different threads. Here is a comprehensive guide to using Handler:

1. The basic principle of Handler

Handler works based on message queues (MessageQueue) and loopers (Looper), and mainly consists of:

  • Message: Message object carrying data
  • MessageQueue: Message queue, storing pending messages
  • Looper: Message loop, continuously fetching messages from the queue for processing
  • Handler: Interface for sending and processing messages

2. Basic usage

1. Create Handler (main thread)

// Create a Handler in the main thread will automatically associate the Looper of the main threadHandler mainHandler = new Handler(()) {
    @Override
    public void handleMessage(Message msg) {
        // Process messages        switch () {
            case 1:
                String text = (String) ;
                (text);
                break;
        }
    }
};

2. Send a message

// Send empty message(1);
// Send a message with whatMessage msg = ();
 = 2;
 = "Hello Handler";
(msg);
// Delayed send(1, 1000); // Send in 1 second(msg, 2000); // 2Send in seconds

3. Use Handler on child thread

new Thread(() -> {
    // Create a Looper for the current thread    ();
    Handler threadHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // Process child thread messages        }
    };
    // Start message loop    ();
}).start();

3. Common usage scenarios of Handler

1. Update the UI

new Thread(() -> {
    // Simulation time-consuming operation    try {
        (1000);
        // Send a message to the main thread to update the UI through Handler        Message msg = ();
         = 1;
         = "Updated Text";
        (msg);
    } catch (InterruptedException e) {
        ();
    }
}).start();

2. Timing tasks

// Delay execution(() -> {
    (this, "Execute in 5 seconds", Toast.LENGTH_SHORT).show();
}, 5000);
// Loop executionfinal Runnable runnable = new Runnable() {
    @Override
    public void run() {
        // Execute tasks        ("Handler", "Execute every 1 second");
        // Post again to implement the loop        (this, 1000);
    }
};
(runnable, 1000);
// Cancel the timing task(runnable);

3. Inter-thread communication

// Worker threadclass WorkerThread extends Thread {
    public Handler workerHandler;
    @Override
    public void run() {
        ();
        workerHandler = new Handler(()) {
            @Override
            public void handleMessage(Message msg) {
                // Process messages from the main thread                String task = (String) ;
                ("WorkerThread", "Execute Task: " + task);
                // Can pass the result back to the main thread                Message resultMsg = ();
                 = 2;
                 = task + " Finish";
                (resultMsg);
            }
        };
        ();
    }
}
// The main thread sends tasks to the worker threadWorkerThread worker = new WorkerThread();
();
// Wait for workerHandler to initializenew Handler().postDelayed(() -> {
    if ( != null) {
        Message msg = ();
         = "Download File";
        (msg);
    }
}, 1000);

4. Advanced usage

1. Use HandlerThread

// Create HandlerThreadHandlerThread handlerThread = new HandlerThread("MyHandlerThread");
();
// Get the HandlerThread Looper to create HandlerHandler threadHandler = new Handler(()) {
    @Override
    public void handleMessage(Message msg) {
        // Process messages in background thread    }
};
// Send a message(() -> {
    // Execute in HandlerThread});
// Release resources when exiting();

2. Avoid memory leaks

// Use static inner class + weak referenceprivate static class SafeHandler extends Handler {
    private final WeakReference<Activity> activityRef;
    public SafeHandler(Activity activity) {
        super(());
         = new WeakReference<>(activity);
    }
    @Override
    public void handleMessage(Message msg) {
        Activity activity = ();
        if (activity != null && !()) {
            // Securely process messages        }
    }
}
// Use in Activityprivate SafeHandler safeHandler = new SafeHandler(this);

3. Optimization using Message

// Reuse Message objects (recommended)Message msg = (WHAT_ARG, obj);
(msg);
// Set callback instead of inheriting Handler((handler, () -> {
    // Callback processing}));

5. Things to note

  • Thread safety: Handler is bound to the thread that created it, and cannot be used directly across threads
  • Memory leak: Non-static Handler internal class will hold external class references, and the callback must be removed when the Activity is destroyed
  • Looper Preparation: The child thread must call () first when using Handler
  • Message accumulation: Avoid sending too many messages causing blockage of message queue
  • Clean up in time: Remove all callbacks in onDestroy()
@Override
protected void onDestroy() {
    ();
    (null);
    if (handlerThread != null) {
        ();
    }
}

This is the end of this article about the detailed explanation of the usage of Android Handler. For more related content on Android Handler, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!