我使用了 HandlerThread,然后使用它的 looper 创建了一个新的 Handler,以便它可以在非 UI 线程上运行操作。在发布到处理程序的可运行文件中,我添加了要显示的 Toast 消息。我预计这会导致问题,因为您无法从非 UI 线程中触摸 UI 组件,但它仍然有效,并且仍在显示 toast。谁能解释为什么从非 UI 线程显示 toast ?
//Inside a Fragment class
private Handler handler;
private HandlerThread mHandlerThread = null;
public void startHandlerThread() {
mHandlerThread = new HandlerThread("HandlerThread");
mHandlerThread.start();
handler = new Handler(mHandlerThread.getLooper());
}
private Runnable submitRunnable = new Runnable() {
@Override
public void run() {
//do some long running operations here
//Thread.sleep(2000);
//Check whether currentLooper is the Main thread looper
boolean isUiThread = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
? Looper.getMainLooper().isCurrentThread()
: Thread.currentThread() == Looper.getMainLooper().getThread();
if (isUiThread) {
// You are on the UI thread
Log.d("Thread", "Main thread");
} else {
// You are on the non-UI thread
Log.d("Thread", "Not Main thread"); //This will be printed
}
Toast.makeText(getContext(), "toast is shown", Toast.LENGTH_SHORT).show();
}
};
submitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
handler.post(submitRunnable);
}
});
我检查了 Toast.java,发现 looper 使用 Looper.myLooper() 进行了自我初始化。
if (looper == null) {
// Use Looper.myLooper() if looper is not specified.
looper = Looper.myLooper();
}
从文档:
myLooper(): Return the Looper object associated with the current thread.
而currentThread是HandlerThread,不是主线程。因此,我无法理解 toast 是如何从非 UI 线程显示的,或者它是否是我想看的简单的东西。