Wednesday, April 03, 2013

Android Tip - Updating Your UI Safely on a Separate Thread

Very often, in your Android applications, you have several threads running in the background. And sometimes you need to update your UI (or perhaps display a Toast) from a background thread. In this case, you need to take special care to ensure that the update is done in a thread-safe manner. If not, your application will simply crash.

To update your UI in a thread-safe fashion, use the runOnUiThread() method:

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        Toast.makeText(getApplicationContext(),
            "Some message to display", Toast.LENGTH_LONG).show();
    }
});

No comments: