Following on from part 1, where we showed screens which updated only on finger press events, its time to get dynamic. We'll build on the first tutorial and make the numbers spin up all the time. This is a little more complex because it introduces a fundamental rule regarding threading on Android - one which was smartly side-stepped in part 1.
A finger tap will still bring up new counters - the difference is we will now see them spinning up in response to the background thread.
There was a reason the counters didn't continuously update in the first threading tutorial - it was to avoid the thorny issue seasoned UI developers are only too well aware of: you cannot update the UI directly from a thread. This is a golden rule on Android. There is nothing in the code stopping you trying - no syntax errors will be thrown, and your code will attempt to run. Thats because these are normal java objects and obey all the regular method calling rules. When you do try it though, your app will crash spectacularly.
The reason for this is the UI is updated from the main thread of all Android apps which expects to have exclusive access to it. That means the internal state mechanisms are only updated by known system code in a controlled manner. When a separate thread attempts to access this, which by its nature is asynchronous so will be interrupting the main thread at any time, it would need to disturb these internal state mechanisms. If this were to happen, it would not have informed the main thread of what it had done. So the main thread finds the nice, ordered internal data structures it has been maintaining are being changed without its knowledge - it will quickly cause havoc to the whole application.
This sounds bad - it seems we can have all the wonders of simultaneous parallel code execution but we can't see what anything these separate threads do? Not quite. The rule is the extra threads cannot make UI calls directly - they can make as many calls into the main thread as they want as long as they don't touch the UI. A great way of making these calls back is to send it a Message. This is a controlled bundle of data which is created by the Message sender and aimed at any object with a Message receiver. When it is fired the receiver can extract this data and make use of it. Theres a MessageQueue tutorial available.
So this is a great way forward for our example - we could get the background thread to continue updating the counters but send the main thread a Message each time there is a new value. The main thread would handle this message by updating the counters, and in effect we will see them all updating continuously.
Portions are modifications based on work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License. Android Academy is independent from Google. All trademarks acknowledged.