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));