在任何情况下显示吐司

Show Toast in any circumstances

我写了这个辅助方法来显示来自任何地方的敬酒。在我将它添加到我的助手库集合之前,有人可以看一下并说一切正常吗?

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

在这里,ToastOnUIThread class 是:

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

我还没有发现任何问题,但也许 Context 是否是 Activity 的实例并不重要,因为:

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

所以,你只需要它:

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