Android: Show Toast Anywhere
This handles showing a Toast in both main thread or background threads. Meaning you can use it anywhere you like without caring it’s in an Activity, Service, IntentService, AsyncTask or Handler.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
if (Looper.myLooper() == Looper.getMainLooper()) { Toast.makeText(context, massage, Toast.LENGTH_SHORT).show(); } else { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Toast.makeText(context, massage, Toast.LENGTH_SHORT).show(); } }); } |
Put it in an Util class as static method. You can also apply style to the Toast based on themes, or use 3rd party Toast library.