How do you display a Toast from a background thread on Android? How do you display a Toast from a background thread on Android? multithreading multithreading

How do you display a Toast from a background thread on Android?


You can do it by calling an Activity's runOnUiThread method from your thread:

activity.runOnUiThread(new Runnable() {    public void run() {        Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();    }});


I like to have a method in my activity called showToast which I can call from anywhere...

public void showToast(final String toast){    runOnUiThread(() -> Toast.makeText(MyActivity.this, toast, Toast.LENGTH_SHORT).show());}

I then most frequently call it from within MyActivity on any thread like this...

showToast(getString(R.string.MyMessage));


This is similar to other answers, however updated for new available apis and much cleaner. Also, does not assume you're in an Activity Context.

public class MyService extends AnyContextSubclass {    public void postToastMessage(final String message) {        Handler handler = new Handler(Looper.getMainLooper());        handler.post(new Runnable() {            @Override            public void run() {                Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();            }        });    }}