今天用实践郭大神《第一行代码》上第11章基于百度定位服务的时候,发现返回的
定位信息在调用TextView的setText()方法时应用崩了,查看日志发现是非主线程
更新UI导致。
原因:
MyLocationListener继承了BDLocationListener,它里面的方法 onReciveLocation是异步事件,即会开启一个线程来连接baidu获取定位 信息,防止主线程被阻塞,《第一行代码》中直接在该方法中执textView 的setText()方法,显然会出现问题。
解决方法:
很简单,用该书第10章的一个示例即可。建立一个标志,定义一个全局 StringBuilder,在获取到定位信息后新建一个Message携带1,然后主 线程判断Message中的标志,然后再将StringBuilder传入setText()即可。
代码:
StringBuilder currentPosition;
private static final int UPDATE_TEXT = 1;
private Handler handler = new Handler(){
public void handleMessage(Message msg){
switch (msg.what){
case UPDATE_TEXT:
textView.setText(currentPosition);
currentPosition.delete(0,currentPosition.length());
break;
default:
break;
}
}
};
public class MyLocationListener implements BDLocationListener{
@Override
public void onReceiveLocation(BDLocation bdLocation) {
currentPosition = new StringBuilder();
currentPosition.append("纬度:").append(bdLocation.getLatitude()).append("\n");
currentPosition.append("经线:").append(bdLocation.getLongitude()).append("\n");
currentPosition.append("定位方式:");
if(bdLocation.getLocType() == BDLocation.TypeGpsLocation){
currentPosition.append("GPS");
}else if (bdLocation.getLocType() == BDLocation.TypeNetWorkLocation){
currentPosition.append("网络");
}
Message message = new Message();
message.what = UPDATE_TEXT;
handler.sendMessage(message);
}
还有一个小问题就是定位经常失败,最后发现是自己当初注册AK时,包名
写错了,尴尬……