thread = new Thread() {
public void run() {
super.run();
System.out.println("run:" + Thread.currentThread().getName());
Looper.prepare();
handler = new Handler();
Looper.loop();
};
};
thread.start();
然后
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MActivity.this,Thread.currentThread().getName(),0).show();
}
});
代码运行正确。
但是 Toast 显示出来的是 "Thread-217"。
这意味着该 Toast 是从非 UI 线程中显示。
为什么会这样?
非常抱歉,我知道答案了。Toast 是一个特殊的 UI 元素,可以从任何线程中显示。但是其他 UI 元素,例如 Button 和 TextView ,只能在 UI 线程中操作。
所以,我的代码运行正确,但是当你将 Toast 更改为 Button 时,它会崩溃。