Login     Sign Up
Cyril Sermon (@admin)
9 months ago
41 Views

Synchronizing Threads for GUI Operations

Whenever you’re using background threads in a GUI environment, it’s important to synchronize child threads with the main application (GUI) thread before creating or modifying graphical components.

The Handler class allows you to post methods onto the thread in which the Handler was created. Using the Handler class, you can post updates to the User Interface from a background thread using the Post method. The following example shows the outline for using the Handler to update the GUI thread:

Initialize a handler on the main thread.

private Handler handler = new Handler();

private void mainProcessing() {

Thread thread = new Thread(null, doBackgroundThreadProcessing, “Background”);

private Runnable doBackgroundThreadProcessing = new Runnable() { public void run() {

backgroundThreadProcessing();

}

};

Method which does some processing in the background.

private void backgroundThreadProcessing() {

[ ... Time consuming operations ... ] handler.post(doUpdateGUI);

}

Runnable that executes the update GUI method.

 private Runnable doUpdateGUI = new Runnable() {

public void run() { updateGUI();

}

};

private void updateGUI() {

[ ... Open a dialog or modify a GUI element ... ]

}

The Handler class lets you delay posts or execute them at a specific time, using the postDelayed and postAtTime methods, respectively.

In the specific case of actions that modify Views, the UIThreadUtilities class provides the runOnUIThread method, which lets you force a method to execute on the same thread as the speci-fied View, Activity, or Dialog.

Within your application components, Notifications and Intents are always received and handled on the GUI thread. In all other cases, operations that explicitly interact with objects created on the GUI thread (such as Views) or that display messages (like Toasts) must be invoked on the main thread.