編輯:關於 Android 程式設計
這幾天研究了一下安卓端調用百度地圖做定位的問題,發現官方示例對「持續定位」這塊講得比較含糊,於是折騰幾次之後把細節補充清楚,方便大家少走彎路。官方示例地址:https://lbsyun.baidu.com/index.php?title=android-locsdk/guide/v5-0
關於如何配置百度地圖的基礎環境,上面那個地址已經寫得很詳細,這裡不再重複。下面直接看代碼:
package com.example.andoridloca; import java.util.List; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.location.BDNotifyListener;//假如用到位置提醒功能,需要import該類 import com.baidu.location.LocationClientOption.LocationMode; import com.baidu.location.Poi; import com.baidu.mapapi.SDKInitializer; import com.baidu.mapapi.map.MapView; public class MainActivity extends Activity implements OnClickListener{ MapView mMapView = null; public static final String TAG="mian"; StringBuffer sb = new StringBuffer(256); public StringBuilder builder=new StringBuilder(); private Button bt1; private TextView tv1; private DBtools DBhelper; boolean isOpenLocation=false; public LocationClient mLocationClient = null; public BDLocationListener myListener = new MyLocationListener(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SDKInitializer.initialize(getApplicationContext()); setContentView(R.layout.activity_main); DBhelper = new DBtools(this); tv1=(TextView) findViewById(R.id.textView1); tv1.setMovementMethod(new ScrollingMovementMethod()); bt1=(Button) findViewById(R.id.button1); bt1.setOnClickListener(this); mMapView = (MapView) findViewById(R.id.bmapView); mLocationClient = new LocationClient(getApplicationContext()); //聲明LocationClient類 mLocationClient.registerLocationListener( myListener ); //注冊監聽函數 initLocation(); } private void initLocation(){ LocationClientOption option = new LocationClientOption(); option.setLocationMode(LocationMode.Hight_Accuracy );//可選,默認高精度,設置定位模式,高精度,低功耗,僅設備 option.setCoorType("bd09ll");//可選,默認gcj02,設置返回的定位結果坐標系 int span=0; option.setScanSpan(span);//可選,默認0,即僅定位一次,設置發起定位請求的間隔需要大於等於1000ms才是有效的 option.setIsNeedAddress(true);//可選,設置是否需要地址信息,默認不需要 option.setOpenGps(true);//可選,默認false,設置是否使用gps option.setLocationNotify(true);//可選,默認false,設置是否當gps有效時按照1S1次頻率輸出GPS結果 option.setIsNeedLocationDescribe(true);//可選,默認false,設置是否需要位置語義化結果,可以在BDLocation.getLocationDescribe裡得到,結果類似於“在北京天安門附近” option.setIsNeedLocationPoiList(true);//可選,默認false,設置是否需要POI結果,可以在BDLocation.getPoiList裡得到 option.setIgnoreKillProcess(false);//可選,默認true,定位SDK內部是一個SERVICE,並放到了獨立進程,設置是否在stop的時候殺死這個進程,默認不殺死 option.SetIgnoreCacheException(false);//可選,默認false,設置是否收集CRASH信息,默認收集 option.setEnableSimulateGps(false);//可選,默認false,設置是否需要過濾gps仿真結果,默認需要 mLocationClient.setLocOption(option); } @Override protected void onDestroy() { super.onDestroy(); //在activity執行onDestroy時執行mMapView.onDestroy(),實現地圖生命周期管理 mMapView.onDestroy(); } @Override protected void onResume() { super.onResume(); //在activity執行onResume時執行mMapView. onResume (),實現地圖生命周期管理 mMapView.onResume(); } @Override protected void onPause() { super.onPause(); //在activity執行onPause時執行mMapView. onPause (),實現地圖生命周期管理 mMapView.onPause(); } public class MyLocationListener implements BDLocationListener { @Override public void onReceiveLocation(BDLocation location) { //Receive Location StringBuffer sb = new StringBuffer(256); sb.append("time : "); sb.append(location.getTime()); sb.append("\nerror code : "); sb.append(location.getLocType()); sb.append("\nlatitude : "); sb.append(location.getLatitude()); sb.append("\nlontitude : "); sb.append(location.getLongitude()); sb.append("\nradius : "); sb.append(location.getRadius()); if (location.getLocType() == BDLocation.TypeGpsLocation){// GPS定位結果 sb.append("\nspeed : "); sb.append(location.getSpeed());// 單位:公裡每小時 sb.append("\nsatellite : "); sb.append(location.getSatelliteNumber()); sb.append("\nheight : "); sb.append(location.getAltitude());// 單位:米 sb.append("\ndirection : "); sb.append(location.getDirection());// 單位度 sb.append("\naddr : "); sb.append(location.getAddrStr()); sb.append("\ndescribe : "); sb.append("gps定位成功"); } else if (location.getLocType() == BDLocation.TypeNetWorkLocation){// 網絡定位結果 sb.append("\naddr : "); sb.append(location.getAddrStr()); //運營商信息 sb.append("\noperationers : "); sb.append(location.getOperators()); sb.append("\ndescribe : "); sb.append("網絡定位成功"); } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 離線定位結果 sb.append("\ndescribe : "); sb.append("離線定位成功,離線定位結果也是有效的"); } else if (location.getLocType() == BDLocation.TypeServerError) { sb.append("\ndescribe : "); sb.append("服務端網絡定位失敗,可以反饋IMEI號和大體定位時間到loc-bugs@baidu.com,會有人追查原因"); } else if (location.getLocType() == BDLocation.TypeNetWorkException) { sb.append("\ndescribe : "); sb.append("網絡不同導致定位失敗,請檢查網絡是否通暢"); } else if (location.getLocType() == BDLocation.TypeCriteriaException) { sb.append("\ndescribe : "); sb.append("無法獲取有效定位依據導致定位失敗,一般是由於手機的原因,處於飛行模式下一般會造成這種結果,可以試著重啟手機"); } sb.append("\nlocationdescribe : "); sb.append(location.getLocationDescribe());// 位置語義化信息 List<Poi> list = location.getPoiList();// POI數據 if (list != null) { sb.append("\npoilist size = : "); sb.append(list.size()); for (Poi p : list) { sb.append("\npoi= : "); sb.append(p.getId() + " " + p.getName() + " " + p.getRank()); } } Log.i("BaiduLocationApiDem", sb.toString()); DBtools dbhelper=new DBtools(getApplicationContext()); ContentValues initialValues = new ContentValues(); initialValues.put("shijian",location.getTime()); initialValues.put("didian",location.getLatitude()+"--"+location.getLongitude()); dbhelper.open(); dbhelper.insert("path",initialValues); dbhelper.close(); tv1.setText(sb.toString()); } } @Override public void onClick(View arg0) { Thread mytime=new Thread(new ThreadShow()); if(isOpenLocation){ mLocationClient.stop(); isOpenLocation=false; } else{ Toast.makeText(getApplicationContext(), "開啟", Toast.LENGTH_SHORT).show(); isOpenLocation=true; //mLocationClient.start(); mytime.start(); } } // handler類接收數據 Handler handler = new Handler() { public void handleMessage(Message msg) { if (msg.what == 1) { Log.i("BaiduLocationApiDem", "加以"); mLocationClient.start(); mLocationClient.requestLocation(); } }; }; // 線程類 class ThreadShow implements Runnable { @Override public void run() { // TODO Auto-generated method stub while (isOpenLocation) { try { mLocationClient.stop(); Thread.sleep(2000); Message msg = new Message(); msg.what = 1; handler.sendMessage(msg); // System.out.println("send..."); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("thread error..."); } } } } } 這裡有三個方法需要單獨說明,因為持續定位能不能跑通,全靠它們的配合:
mLocationClient.start() 用於開啟定位,mLocationClient.requestLocation() 用於主動觸發一次 SDK 內部的定位邏輯。從官方文檔的表述看兩者作用相近,實測也都會走到 MyLocationListener 的邏輯裡;mLocationClient.stop() 則是停止定位。要做持續定位,就得讓 start() 和 stop() 反覆配合,代碼裡用線程實現的正是這件事。
切記不要把 start() 和 stop() 寫在一起:
//某段代碼如果是這樣的話按照邏輯韓式會將mLocationClient所屬類的裡面邏輯代碼執行一遍,具體見MainAvtivity裡面的MyLocationListener類內容,但是實際上是不會執行的 mLocationClient.start(); mLocationClient.stop();
按邏輯推,這兩行連寫應該會觸發一次定位回調,但實際上不會執行——start 之後立刻 stop,請求就被取消了。所以我在 MainActivity 裡用線程循環地執行 start 與 stop,以此規避這個問題,最終實現持續定位。
順帶附上布局文件,方便對照:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://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>
權限之類的配置照官方地址操作就行。
還有一點值得補充:上面這種「start-stop 循環」的寫法本質上是繞開 SDK 的行為限制,並不是官方推薦用法。更規範的持續定位做法是把 setScanSpan 設為大於等於 1000 的間隔值,讓 SDK 內部自己按頻率回調,代碼更簡潔也更省電。
另外,本文開發環境是 Android 4.2,真機與模擬器在定位時間間隔上存在一些誤差,具體原因暫未查清,遇到類似現象可以留意一下。
以上就是本文的全部內容,希望對大家的學習或工作有所幫助。
Android 4.4 KitKat Phone 工作流程淺析(九):狀態通知流程
概要 當手機 Modem 狀態發生變化後,會將狀態變化信息上報到上層。結合《Android 4.4 KitKat Phone 工作流程淺析(八):Phone 狀態分析》與
Android 自訂下雪動畫效果:雪花類、SnowView 與全屏布局
天氣冷的時候不太想出門,剛好適合窩著寫點小東西。替 App 加上一層緩緩飄落的雪,是冬天主題、節慶活動頁最常出現的點綴。整個效果的骨架其實只有三件事:把狀態欄藏起來讓圖片
Android NDK 開發入門:從 JNI 概念到第一個 so 庫
一、JNI 是什麼 JNI 是 Java Native Interface 的縮寫,它定義了一套讓 Java 程式碼與原生程式碼(以 C/C++ 撰寫)互相溝通的方式。在
Android UI 優化:用 ViewStub 實現布局延遲加載
問題場景 界面裡有些元素並不是首屏就需要:例如「展開更多篩選條件」的面板、只在特定狀態下出現的浮層、用戶點擊後才展示的詳情區塊。如果把它們和主布局一起 inflate,不