Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Resolving Handler Message Delays When Combined with Thread Blocking in Android Background Tasks

Tech May 13 2

Integrating background polling with UI updates in Android often leads to timing discrepancies when developers combine Thread.sleep() with Handler message dispatching within the same execution scope. In this scenario, messages intended to trigger immediate interface changes appear to queue up and execute only after the blocking sleep duration completes, resulting in a frozen interface and desynchronized hardware control.

The underlying issue stems from coupling asynchronous callbacks with synchronous thread blocking. When Thread.sleep() is invoked inside an async listener, it halts the worker thread entirely. Although Handler.sendMessage() posts tasks to the main thread's message queue independently, the blocked worker thread cannot process subsequent poll cycles or state transitions efficiently. This creates a bottleneck where hardware commands, UI updates, and thread delays compete for the same execution context, causing messages to be processed in batches only after the sleep releases.

To resolve this, the polling cycle must be decoupled from the actuation sequence. The solution introduces a state-driven flag that separates the 17-second hardware delay from the immediate RFID reading logic. The background loop continuously checks this flag. If the flag indicates an active operation, the loop handles the delay and state reset directly. Otherrwise, it proceeds with standard polling. This ensures the worker thread remains responsive, UI updates are dispatched immediately, and hardware control follows a predictable timeline.

Background Controller Implementation

public class AccessController {
    private final Handler uiDispatcher;
    private final String targetEpc;
    private volatile boolean isActuating = false;
    private String lastProcessedEpc = "";

    public AccessController(Handler uiHandler, String knownEpc) {
        this.uiDispatcher = uiHandler;
        this.targetEpc = knownEpc;
    }

    public void initializePollingCycle() {
        Thread scanningThread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    if (isActuating) {
                        Thread.sleep(17000);
                        deactivateHardwareRelays();
                        dispatchUiUpdate(0);
                        isActuating = false;
                        lastProcessedEpc = "EMPTY";
                    } else {
                        Thread.sleep(3000);
                        executeRfidScan();
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        }, "Background-Scanner");
        scanningThread.start();
    }

    private void executeRfidScan() {
        rfidModule.readSingleTag(new TagListener() {
            @Override
            public void onRead(String scannedEpc) {
                if (!scannedEpc.equals(lastProcessedEpc)) {
                    lastProcessedEpc = scannedEpc;
                    if (scannedEpc.equals(targetEpc)) {
                        activateHardwareRelays();
                        dispatchUiUpdate(1);
                        isActuating = true;
                    } else {
                        dispatchUiUpdate(0);
                    }
                }
            }
            @Override
            public void onError(Exception error) { }
        });
    }

    private void dispatchUiUpdate(int statusFlag) {
        uiDispatcher.obtainMessage(statusFlag, null).sendToTarget();
    }
}

Main Thread UI Handler

Handler mainUiThread = new Handler(Looper.getMainLooper(), message -> {
    switch (message.what) {
        case 0:
            Toast.makeText(activityContext, "Access Denied", Toast.LENGTH_SHORT).show();
            statusIndicator.setImageResource(R.drawable.ic_light_red);
            barrierGate.setImageResource(R.drawable.ic_gate_closed);
            break;
        case 1:
            Toast.makeText(activityContext, "Access Granted", Toast.LENGTH_SHORT).show();
            statusIndicator.setImageResource(R.drawable.ic_light_green);
            barrierGate.setImageResource(R.drawable.ic_gate_open);
            break;
    }
    return true;
});

Hardware Control Abstraction

private void activateHardwareRelays() {
    modbusController.setPin(1, true);
    modbusController.setPin(0, false);
    modbusController.setPin(2, false);
    modbusController.setPin(5, false);
    modbusController.setPin(6, true);
}

private void deactivateHardwareRelays() {
    modbusController.setPin(5, true);
    modbusController.setPin(6, false);
    modbusController.setPin(1, false);
    modbusController.setPin(0, true);
    modbusController.setPin(2, false);
}

The refactored structure eliminates nested sleep calls within asynchronous callbacks. By elevating the delay logic to the primary loop and utilizing a volatile state flag, the background thread avoids blocking during critical UI transitions. Hardware commands execute immediately upon tag verification, while the extended retraction sequence runs independently.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.