Search code examples
androidtoastandroid-toast

Show Toast in any circumstances


I wrote this helper method to show a toast from anywhere. Can someone please take a look and say it is all OK before I add it to my helper library collection?

static void showToast(Context ctx, CharSequence msg) {

    Looper mainLooper = Looper.getMainLooper();
    Runnable r = new ToastOnUIThread(ctx, msg);

    boolean onUiThread;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        onUiThread = mainLooper.isCurrentThread();
    } else {
        onUiThread = Thread.currentThread() == mainLooper.getThread();
    }

    if (!onUiThread) {
        if (ctx instanceof Activity) {
            ((Activity) ctx).runOnUiThread(r);
        } else {
            Handler h = new Handler(mainLooper);
            h.post(r);
        }
    } else {
        r.run();
    }
}

Here, the ToastOnUIThread class is:

private static class ToastOnUIThread implements Runnable {

    private Context ctx;
    private CharSequence msg;

    private ToastOnUIThread(Context ctx, CharSequence msg) {

        this.ctx = ctx;
        this.msg = msg;
    }

    public void run() {

        Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
    }
};

Solution

  • I haven't found any issue yet, but maybe it doesn't matter whether the Context is an instance of Activity or not, because:

    public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }
    

    So, you only need it:

    Handler h = new Handler(mainLooper);
    h.post(r);