-
Notifications
You must be signed in to change notification settings - Fork 73
6. Getting a "real time" activity to work
When programming an activity that needs to update the UI real time, such as the ElmTest, there are a few things "Android" that you need to keep in mind.
Literally everything you do that requires some sort of time out or sleeping (which basically means everything that interfaces with another device or is waiting for something to happen), needs to run in a separate thread. This ensures your Android UI does not lock up. Here is how to do it:
new Thread(new Runnable() {
@Override
public void run() {
doSomething();
}
}).start();
The code in doSomething will run on it's own while this code block simply finishes. It is now safe to do i.e. Thread.Sleep() in doSomething without freezing your device.
Unfortunately, updating the UI is not trivial anymore now in doSomething. Anything on the UI needs to be done through the UI thread and we didn't want to i.e. Sleep on that one, contradiction! To mitigate this, you have to update the UI in a yet again separate thread, the global UI thread. As an example, here is the code that is called by doSomething to append a string to a TextView. Note that textview is a private Textview defined in the overall Class we're working on and it represents the field on the screen we are appending.
private void appendResult (String str) {
final String localStr = str; // a final String is needed in method run.
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.append(localStr);
}
});
}
This little piece of code ensures the appending is immediately represented on the UI, instead of the UI being updated only when all other code finishes.
Also note that starting a normal thread and attaching something to the UI thread both look quite similar, but they aren't. A normal thread is created and then started with it's .start() method. Forgetting to start the thread is an easy mistake to make. Attaching to the UI is done with runOnUiThread. No starting needed (or possible).
It looks horribly complicated (and it is). Only after fighting for a day or two it really all made sense and I have tried to explain that here. Hope it helps and saves you a few hours.