編輯:關於 Android 開發
前陣子研究了手機端 Android 地圖開發,發現百度官方 Demo 在「持續定位」這塊講得不太透徹。折騰幾次之後,我把要點整理得更清楚一些,希望能幫到正在入門的朋友。文中若有不足之處,歡迎在評論區指正。官方示例地址:百度定位 SDK 指南。
上面這個網址已經把 Android 的環境配置講得很詳細,這裡不再贅述。先看一段完整程式碼:
package com.example.andoridloca;
import java.util.List;
import android.app.Activity;
import android.content.ContentValues;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
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.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";
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"); // 座標系
int span = 0;
option.setScanSpan(span); // 0 表示僅定位一次;欲持續定位需 ≥1000ms
option.setIsNeedAddress(true); // 是否需要地址資訊
option.setOpenGps(true); // 是否使用 GPS
option.setLocationNotify(true); // GPS 有效時按 1S1 次輸出
option.setIsNeedLocationDescribe(true); // 位置語義化結果
option.setIsNeedLocationPoiList(true); // POI 結果
option.setIgnoreKillProcess(false);
option.SetIgnoreCacheException(false);
option.setEnableSimulateGps(false);
mLocationClient.setLocOption(option);
}
@Override
protected void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mMapView.onPause();
}
public class MyLocationListener implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
StringBuffer sb = new StringBuffer(256);
sb.append("time : ").append(location.getTime());
sb.append("\nerror code : ").append(location.getLocType());
sb.append("\nlatitude : ").append(location.getLatitude());
sb.append("\nlontitude : ").append(location.getLongitude());
sb.append("\nradius : ").append(location.getRadius());
if (location.getLocType() == BDLocation.TypeGpsLocation) {
sb.append("\nspeed : ").append(location.getSpeed());
sb.append("\nsatellite : ").append(location.getSatelliteNumber());
sb.append("\nheight : ").append(location.getAltitude());
sb.append("\ndirection : ").append(location.getDirection());
sb.append("\naddr : ").append(location.getAddrStr());
sb.append("\ndescribe : ").append("gps定位成功");
} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
sb.append("\naddr : ").append(location.getAddrStr());
sb.append("\noperationers : ").append(location.getOperators());
sb.append("\ndescribe : ").append("網絡定位成功");
} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {
sb.append("\ndescribe : ").append("離線定位成功,離線定位結果也是有效的");
} else if (location.getLocType() == BDLocation.TypeServerError) {
sb.append("\ndescribe : ").append("服務端網絡定位失敗");
} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
sb.append("\ndescribe : ").append("網絡不同導致定位失敗,請檢查網絡");
} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
sb.append("\ndescribe : ").append("無法獲取有效定位依據,試著重啟手機");
}
sb.append("\nlocationdescribe : ").append(location.getLocationDescribe());
List<Poi> list = location.getPoiList();
if (list != null) {
sb.append("\npoilist size = : ").append(list.size());
for (Poi p : list) {
sb.append("\npoi= : ").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;
mytime.start();
}
}
// handler 接收數據
Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 1) {
mLocationClient.start();
mLocationClient.requestLocation();
}
}
};
// 線程類
class ThreadShow implements Runnable {
@Override
public void run() {
while (isOpenLocation) {
try {
mLocationClient.stop();
Thread.sleep(2000);
Message msg = new Message();
msg.what = 1;
handler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
持續定位時,mLocationClient.start()、mLocationClient.stop() 與 mLocationClient.requestLocation() 這三者的配合至關重要:
start():開啟定位。requestLocation():主動觸發 SDK 內部的定位邏輯。stop():停止定位,需與 start() 搭配使用。切記不要把 start() 和 stop() 緊挨著寫在一起,否則定位邏輯不會真正執行:
// 這樣寫,理論上會執行一遍定位邏輯,但實際上不會執行 mLocationClient.start(); mLocationClient.stop();
因此在 MainActivity 裡,我用一個執行緒反覆呼叫 start 與 stop(中間 sleep 間隔),就能消除上述問題,最終實現持續定位。
<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>
權限等其餘配置直接照官方文件走即可。另外補充一點:本文使用 Android 4.2 開發,真機與模擬器在定位時間間隔上會有些許誤差,具體原因暫未深究。
Android Toolbar 與 DrawerLayout 搭配筆記:讓 NavigationView 正確落在 Toolbar 下方
Android Toolbar 與 DrawerLayout 搭配筆記在 Android Studio 產生的 Navigation Drawer Activity 範本
Android 開發技巧:大圖裁剪與旋轉圖處理完整方案
Android 開發技巧:大圖裁剪與旋轉圖處理完整方案 本篇承接上一篇《Android 開發技巧——定製仿微信圖片裁剪控件》,先簡單介紹該裁剪控件的使用方式,再詳細說明如
修改 Android 編譯資源 ID:從 aapt 源碼到插件化應用
技術準備 Android 編譯後會產生 R 檔與 resource.arsc。資源 ID 看似只是 0x7F 開頭的整數,實際上由 PackageId、TypeId 與
Android 插件化(一):改進 MultiDex 動態載入 assets 中的 apk
Android 插件化(一):改進 MultiDex 動態載入 assets 中的 apk 為了解決方法數超過 65535 的問題,Google 建議用 MultiDex