我从后台线程调用一个Handler类。在Handler类中,我试图显示一个toast。理论上它应该完美地工作,因为Handler是将UI任务转发到主UI线程的队列。但是,在我的情况下,我得到例外。
private void firstTimeLogin() {
final LoginUiThreadHandler loginHandler = new LoginUiThreadHandler();
new Thread(new Runnable() {
@Override
public void run() {
Message m = loginHandler.obtainMessage();
Bundle bund = new Bundle();
bund.putInt("loginResult", 1);
m.setData(bund);
loginHandler.handleMessage(m);
}
}).start();
}
private class LoginUiThreadHandler extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int loginResult = msg.getData().getInt("loginResult");
if(loginResult == 0)
Toast.makeText(getActivity().getApplicationContext(), "Login success", Toast.LENGTH_SHORT).show();
}
}
我做错了什么?
答案 0 :(得分:-1)
替换为 -
LoginUiThreadHandler loginHandler = new LoginUiThreadHandler(Looper.getMainLooper());
而不是 -
LoginUiThreadHandler loginHandler = new LoginUiThreadHandler();