解决《第一行代码》中百度定位信息问题

来源:互联网 发布:微交易系统源码下载 编辑:程序博客网 时间:2024/06/05 14:45
    今天用实践郭大神《第一行代码》上第11章基于百度定位服务的时候,发现返回的定位信息在调用TextView的setText()方法时应用崩了,查看日志  发现是非主线程更新UI导致。
  1. 原因:

        MyLocationListener继承了BDLocationListener,它里面的方法onReciveLocation是异步事件,即会开启一个线程来连接baidu获取定位信息,  防止主线程被阻塞,而《第一行代码》中直接在该方法中执行textView的setText()方法,显然会出现问题。
  2. 解决方法:

        很简单,用该书第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时,包名写错了,尴尬……
0 0
原创粉丝点击