Error:Can't create handler inside thread that has not called Looper.prepare()
原代码:
//利用Handler消息传递机制
final Handler myHandler = new Handler(MainActivity.this.getMainLooper()){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 0x123){
//置于此处有问题 (初步估计是线程间问题)
Toast toast = Toast.makeText(MainActivity.this, "祝您旅途愉快!", Toast.LENGTH_LONG);
toast.show();
}
}
};
//发送空消息
myHandler.sendEmptyMessage(0x123);
搜索后发现,原因是此Handler没有Looper。到哪儿去找Looper呢?自己建?
在代码前加入Looper.prepare();,心想这回可以了吧?
没想到依然报错,错误显示,一个主进程只能有一个Looper,要死了。郁闷中...
突然我想到主进程中肯定有Looper,Context.getMainLooper(),再看Handler的实例化时是可以指定Looper的,太爽了,最后代码如下
//利用Handler消息传递机制
final Handler myHandler = new Handler(MainActivity.this.getMainLooper()){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 0x123){
//置于此处有问题 (初步估计是线程间问题)
Toast toast = Toast.makeText(MainActivity.this, "祝您旅途愉快!", Toast.LENGTH_LONG);
toast.show();
}
}
};
//发送空消息
myHandler.sendEmptyMessage(0x123);