Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

在百度地圖開發中實現持續定位:三個關鍵 API 的搭配心得

編輯:關於 Android 開發

百度地圖 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();
                }
            }
        }
    }
}

三個關鍵 API 的搭配

持續定位時,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 開發,真機與模擬器在定位時間間隔上會有些許誤差,具體原因暫未深究。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved