Toast.makeText 方法出错 java.lang.RuntimeException

接手以前同事留下的代码,今天突然出现了一个bug:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

 


而出错的代码就是一个Toast.makeText()方法。

这个方法很常见,但是报错的不多,前两天有过类似的经验,所以很快找到原因:Android中不允许其他线程更新主线程的视图。

修改很简单,创建一个handler,用来处理消息,然后把原来的处理代码放到handler中,调用的时候发送一个消息过去就可以了。

final Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        if(msg.what == -1){
            Toast.makeText(SetActivity.this, "无法连接网络,登录失败", Toast.LENGTH_LONG).show();
        }
    }
};
Message msg = new Message();
msg.what = -1;
handler.sendMessage(msg);

 

posted @ 2013-11-06 17:28  MNight  阅读(2902)  评论(0编辑  收藏  举报