Swapnil
Swapnil

Reputation: 2051

Android: Best practice to ensure that a UI operation is done on UI thread

I have landed into situations where I need to do some the same UI operation (let's say showing of a Toast message) from two different threads. The difference is that the first thread is the UI thread for the activity and the other one is a separate thread that I started to run some background process. The question is that what is the best practice to ensure that the code to show the Toast message is always run from the UI thread. I see here two possibilities.

We have a function which is supposed to show the test message like

private void showToast() {
     Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}

And each time we call this method we ensure that it has to be called on the UI thread for which we can use runOnUiThread()from the place we are calling showToast().

The other option is to ensure that the code to show the Toastis run on the UI thread within the method showToast() itself. SOmething like this:

private void showToast() {
         runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, message, Toast.LENGTH_LONG).show();
            }
        });
    }

Which is the preferred practice and why?

Upvotes: 1

Views: 1107

Answers (3)

Use the second option is a useful but the Android patterns recommend to use an AsyncTask thread when you are working with threads because you have 3 different ways to use UI thread (onPreExecute, onProgressUpdates and onPostExecute).

https://developer.android.com/reference/android/os/AsyncTask.html

Upvotes: 0

Yurii Tsap
Yurii Tsap

Reputation: 3744

If you are asking how to determine if we currently are on UI thread then I recommend to do this such way :

Looper.myLooper() == Looper.getMainLooper()

This will return true if we are on UI thread. Otherwise you can search more deeply in this direction : https://developer.android.com/training/multiple-threads/communicate-ui.html

Upvotes: 1

GoneUp
GoneUp

Reputation: 385

Use the second option. If you are already on the UI-Thread the action is just executed in the same context. Reference

Upvotes: 1

Related Questions