Thread safe way of displaying Toast Application Wide

suggest change
public class MainApplication extends Application {
    private static Context context; //application context

    private Handler mainThreadHandler;
    private Toast toast;

    public Handler getMainThreadHandler() {
        if (mainThreadHandler == null) {
            mainThreadHandler = new Handler(Looper.getMainLooper());
        return mainThreadHandler;

    @Override public void onCreate() {
        context = this;
    public static MainApplication getApp(){
        return (MainApplication) context;

     * Thread safe way of displaying toast.
     * @param message
     * @param duration
    public void showToast(final String message, final int duration) {
        getMainThreadHandler().post(new Runnable() {
            public void run() {
                if (!TextUtils.isEmpty(message)) {
                    if (toast != null) {
                        toast.cancel(); //dismiss current toast if visible
                    } else {
                        toast = Toast.makeText(App.this, message, duration);

Remember to add MainApplication in manifest.

Now call it from any thread to display a toast message.

MainApplication.getApp().showToast("Some message", Toast.LENGTH_LONG);

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents