关于如何在安卓的百度地图开发里面简单实现持续定位

提兵百万西湖上,立马吴山第一峰!这篇文章主要讲述关于如何在安卓的百度地图开发里面简单实现持续定位相关的知识,希望能为你提供帮助。
这几天自己研究了关于地手机上面开发安卓地图的问题,发现百度官方示例demo讲解百度持续定位方面还是讲解的有些不清楚,本人研究了几次之后将其弄得更详细以便于让各位方便学习,有不足之处请在评论区指出,官方示例的网址是:http://lbsyun.baidu.com/index.php?title=android-locsdk/guide/v5-0
上面的网址已经将安卓简单配置百度地图环境讲解的很详细了,再次不做赘述了,此外,可能会有人发现

1 package com.example.andoridloca; 2 3 import java.util.List; 4 import java.util.Timer; 5 import java.util.TimerTask; 6 7 import android.app.Activity; 8 import android.content.ContentValues; 9 import android.content.Intent; 10 import android.database.Cursor; 11 import android.os.Bundle; 12 import android.os.Handler; 13 import android.os.Message; 14 import android.text.method.ScrollingMovementMethod; 15 import android.util.Log; 16 import android.view.Menu; 17 import android.view.MenuItem; 18 import android.view.View; 19 import android.view.View.OnClickListener; 20 import android.widget.Button; 21 import android.widget.TextView; 22 import android.widget.Toast; 23 24 import com.baidu.location.BDLocation; 25 import com.baidu.location.BDLocationListener; 26 import com.baidu.location.LocationClient; 27 import com.baidu.location.LocationClientOption; 28 import com.baidu.location.BDNotifyListener; //假如用到位置提醒功能,需要import该类 29 import com.baidu.location.LocationClientOption.LocationMode; 30 import com.baidu.location.Poi; 31 import com.baidu.mapapi.SDKInitializer; 32 import com.baidu.mapapi.map.MapView; 33 34 public class MainActivity extends Activity implements OnClickListener{ 35MapView mMapView = null; 36public static final String TAG="mian"; 37StringBuffer sb = new StringBuffer(256); 38public StringBuilder builder=new StringBuilder(); 39private Button bt1; 40private TextView tv1; 41private DBtools DBhelper; 42boolean isOpenLocation=false; 43public LocationClient mLocationClient = null; 44public BDLocationListener myListener = new MyLocationListener(); 45@Override 46protected void onCreate(Bundle savedInstanceState) { 47super.onCreate(savedInstanceState); 48SDKInitializer.initialize(getApplicationContext()); 49setContentView(R.layout.activity_main); 50DBhelper = new DBtools(this); 51tv1=(TextView) findViewById(R.id.textView1); 52tv1.setMovementMethod(new ScrollingMovementMethod()); 53bt1=(Button) findViewById(R.id.button1); 54bt1.setOnClickListener(this); 55mMapView = (MapView) findViewById(R.id.bmapView); 56mLocationClient = new LocationClient(getApplicationContext()); //声明LocationClient类 57mLocationClient.registerLocationListener( myListener ); //注册监听函数 58initLocation(); 59} 60private void initLocation(){ 61LocationClientOption option = new LocationClientOption(); 62option.setLocationMode(LocationMode.Hight_Accuracy 63 ); //可选,默认高精度,设置定位模式,高精度,低功耗,仅设备 64option.setCoorType("bd09ll"); //可选,默认gcj02,设置返回的定位结果坐标系 65int span=0; 66option.setScanSpan(span); //可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的 67option.setIsNeedAddress(true); //可选,设置是否需要地址信息,默认不需要 68option.setOpenGps(true); //可选,默认false,设置是否使用gps 69option.setLocationNotify(true); //可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果 70option.setIsNeedLocationDescribe(true); //可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近” 71option.setIsNeedLocationPoiList(true); //可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到 72option.setIgnoreKillProcess(false); //可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死 73option.SetIgnoreCacheException(false); //可选,默认false,设置是否收集CRASH信息,默认收集 74option.setEnableSimulateGps(false); //可选,默认false,设置是否需要过滤gps仿真结果,默认需要 75mLocationClient.setLocOption(option); 76} 77@Override 78protected void onDestroy() { 79super.onDestroy(); 80//在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理 81mMapView.onDestroy(); 82} 83@Override 84protected void onResume() { 85super.onResume(); 86//在activity执行onResume时执行mMapView. onResume (),实现地图生命周期管理 87mMapView.onResume(); 88} 89@Override 90protected void onPause() { 91super.onPause(); 92//在activity执行onPause时执行mMapView. onPause (),实现地图生命周期管理 93mMapView.onPause(); 94} 95public class MyLocationListener implements BDLocationListener { 96 97@Override 98public void onReceiveLocation(BDLocation location) { 99//Receive Location 100StringBuffer sb = new StringBuffer(256); 101sb.append("time : "); 102sb.append(location.getTime()); 103sb.append("\nerror code : "); 104sb.append(location.getLocType()); 105sb.append("\nlatitude : "); 106sb.append(location.getLatitude()); 107sb.append("\nlontitude : "); 108sb.append(location.getLongitude()); 109sb.append("\nradius : "); 110sb.append(location.getRadius()); 111if (location.getLocType() == BDLocation.TypeGpsLocation){// GPS定位结果 112sb.append("\nspeed : "); 113sb.append(location.getSpeed()); // 单位:公里每小时 114sb.append("\nsatellite : "); 115sb.append(location.getSatelliteNumber()); 116sb.append("\nheight : "); 117sb.append(location.getAltitude()); // 单位:米 118sb.append("\ndirection : "); 119sb.append(location.getDirection()); // 单位度 120sb.append("\naddr : "); 121sb.append(location.getAddrStr()); 122sb.append("\ndescribe : "); 123sb.append("gps定位成功"); 124 125} else if (location.getLocType() == BDLocation.TypeNetWorkLocation){// 网络定位结果 126sb.append("\naddr : "); 127sb.append(location.getAddrStr()); 128//运营商信息 129sb.append("\noperationers : "); 130sb.append(location.getOperators()); 131sb.append("\ndescribe : "); 132sb.append("网络定位成功"); 133} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果 134sb.append("\ndescribe : "); 135sb.append("离线定位成功,离线定位结果也是有效的"); 136} else if (location.getLocType() == BDLocation.TypeServerError) { 137sb.append("\ndescribe : "); 138sb.append("服务端网络定位失败,可以反馈IMEI号和大体定位时间到[email  protected],会有人追查原因"); 139} else if (location.getLocType() == BDLocation.TypeNetWorkException) { 140sb.append("\ndescribe : "); 141sb.append("网络不同导致定位失败,请检查网络是否通畅"); 142} else if (location.getLocType() == BDLocation.TypeCriteriaException) { 143sb.append("\ndescribe : "); 144sb.append("无法获取有效定位依据导致定位失败,一般是由于手机的原因,处于飞行模式下一般会造成这种结果,可以试着重启手机"); 145} 146sb.append("\nlocationdescribe : "); 147sb.append(location.getLocationDescribe()); // 位置语义化信息 148List< Poi> list = location.getPoiList(); // POI数据 149if (list != null) { 150sb.append("\npoilist size = : "); 151sb.append(list.size()); 152for (Poi p : list) { 153sb.append("\npoi= : "); 154sb.append(p.getId() + " " + p.getName() + " " + p.getRank()); 155} 156} 157Log.i("BaiduLocationApiDem", sb.toString()); 158DBtools dbhelper=new DBtools(getApplicationContext()); 159ContentValues initialValues = new ContentValues(); 160initialValues.put("shijian",location.getTime()); 161initialValues.put("didian",location.getLatitude()+"--"+location.getLongitude()); 162dbhelper.open(); 163dbhelper.insert("path",initialValues); 164dbhelper.close(); 165tv1.setText(sb.toString()); 166} 167} 168 169@Override 170public void onClick(View arg0) { 171Thread mytime=new Thread(new ThreadShow()); 172if(isOpenLocation){ 173mLocationClient.stop(); 174isOpenLocation=false; 175 176} 177else{ 178Toast.makeText(getApplicationContext(), "开启", Toast.LENGTH_SHORT).show(); 179isOpenLocation=true; 180//mLocationClient.start(); 181mytime.start(); 182} 183 184} 185// handler类接收数据 186Handler handler = new Handler() { 187public void handleMessage(Message msg) { 188if (msg.what == 1) { 189Log.i("BaiduLocationApiDem", "加以"); 190mLocationClient.start(); 191mLocationClient.requestLocation(); 192} 193}; 194}; 195// 线程类 196class ThreadShow implements Runnable { 197 198@Override 199public void run() { 200// TODO Auto-generated method stub 201while (isOpenLocation) { 202try { 203mLocationClient.stop(); 204Thread.sleep(2000); 205Message msg = new Message(); 206msg.what = 1; 207handler.sendMessage(msg); 208// System.out.println("send..."); 209} catch (Exception e) { 210// TODO Auto-generated catch block 211e.printStackTrace(); 212System.out.println("thread error..."); 213} 214} 215} 216} 217 218 219} 220 221 222 223 224 225 226

这里面关于mLocationClient.stop(); mLocationClient.start();   mLocationClient.requestLocation(); 这三个函数我有必要讲解一下,因为持续定位时这三个函数的配合使用很重要,官方文档里面解释说mLocationClient.start()函数用于开启定位,mLocationClient.requestLocation()函数用于主动触发定位SDK内部定位逻辑,个人感觉差不多,两个都会执行我的mLocationClient的所属类里面的逻辑代码,可能是我的项目就这样吧,然后是mLocationClient.stop(),此函数用于停止定位,如果持续定位的话,是需要和mLocationClient.start()函数配合使用的,具体在上面的代码里面有展示。
切记不要将mLocationClient.start()和mLocationClient.stop()一起使用,我在网上查询时好像是说一部原因,具体举一个例子吧:
 
1 //某段代码如果是这样的话按照逻辑韩式会将mLocationClient所属类的里面逻辑代码执行一遍,具体见MainAvtivity里面的MyLocationListener类内容,但是实际上是不会执行的 2 mLocationClient.start(); 3 mLocationClient.stop();

 
所以在我的MainActivity里面我使用线程来一遍遍的执行start和stop函数,这样就会消除刚刚说的这种效果,最后就能够实现持续定位了。
 
在此给出我的布局文件配合看看
< LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.newloca.MainActivity" > < RelativeLayout android:layout_width="match_parent" android:layout_height="300dp"> < com.baidu.mapapi.map.MapView android:id="@+id/bmapView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:clickable="true" /> < /RelativeLayout> < TextView android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="150dp" android:scrollbars="vertical" android:background="#f00" android:text="位置信息" /> < RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" > < Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentBottom="true" android:text="获取位置" /> < /RelativeLayout> < /LinearLayout>

其他像权限什么的配置,用最开始给的官方地址里面的就行了
【关于如何在安卓的百度地图开发里面简单实现持续定位】 
顺便说一下,本人是使用的安卓4.2版本开发的,手机真机调试和虚拟机调试在定位的时间间隔上面会有点误差,也不知道什么原因
 

    推荐阅读