Search code examples
javaandroidui-threadandroid-runonuithread

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?


Solution

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