The golden rule of the single-threaded API model is:
Only the event thread can modify the user interface.
In fact, it’s a little more subtle – only a thread holding the user interface event lock can modify the user interface – more on that later, for now just know that almost always the event thread is the one holding that event lock.
This means, if you’re doing anything that will directly result in immediate changes to the UI – pushing (or removing) screens onto the display stack, modifying the visible state of your UI components, painting – you have to do it in the event thread.
Simple, right? Yes, in theory. In practice, it’s not much more difficult – just bear in mind a couple of things.
As I said above the thread that enters your
main method is your application’s event thread. This, combined with the golden rule means that in the initial call to your
main method, you can do all the UI work you want. Often you create your app’s initial screen and push it onto the stack (using
UiApplication.pushScreen) there – or at least in a method that you call directly from there. However, at some point you want to call
enterEventDispatcher or you’ll never get user input. How do you modify the UI after that?
Modifying the UI
Now, the golden rule doesn’t mean that you can’t call any methods on any UI component from any other thread. Anything that gets information (
EditField.getText for example) is fine. Also fine is setting information that may not result in immediate changes. But for most of the built-in UI components – like
LabelField, methods like
setText will result in a change and so must be done while you have the event lock.
How do I know I’m on the event thread
Easy – just
UiApplication.getUiApplication().isEventThread(swift runners) (or
isEventDIspatchThread, which is a static method and does the same thing – both of those methods, by the way, actually reside in
net.rim.device.api.system.Application, which is
UiApplication’s super class).
You will sometimes end up on the event thread – menu items are executed on the event thread for example.
How can I modify my UI?
There are two ways:
1. Use the
invokeAndWait – both of which take a Runnable. Anything in that
runmethod will be executed by the event thread at the next available opportunity. The first method is asynchronous (which means in this case that it returns immediately) the second is synchronous (so waits until your
run method is finished before returning).