Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 技術基礎

百度地圖定位實戰:一句「我在哪」的實現(從零開始學 Android)

編輯:Android 技術基礎

上一章我們已經把百度地圖的基本用法走通了,這一章往前再走一步——做定位,用地圖回答「我在哪」。整體並不難,麻煩多在環境配置和權限聲明這些瑣碎環節上。

準備工作

第一步,下載定位 SDK(Android locSDK3.3):

https://developer.baidu.com/map/static/doc/locSDK3.3.zip

第二步,解壓壓縮包:

至此準備工作結束。

一、工程配置

在工程中新建 libs 文件夾,把開發包裡的 locSDK_3.3.jar 複製到 libs 根目錄,把 liblocSDK3.so 複製到 libs/armeabi 目錄下。完成後的工程結構如下:

接著在「工程屬性 → Java Build Path → Libraries」中選擇 Add External JARs,指定 locSDK_3.3.jar 並確認。兩步做完,定位 SDK 的全部能力就可以正常使用了。

這裡值得強調的是 so 文件的位置:JAR 裡只有 Java 層的接口,真正的定位能力在 native 庫中。so 放錯目錄,編譯能過,運行時才報 UnsatisfiedLinkError。

二、界面設計

打開 res/layout/activity_main.xml,佈局很樸素:一個顯示經緯度的 TextView,加「開始定位」和「停止定位」兩個按鈕。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="開始定位" />

    <Button
        android:id="@+id/stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="停止定位" />

</LinearLayout>

三、程序實現

1. Location.java:繼承 Application 持有定位客戶端

打開 src 下的 Location.java。這個類繼承 Application,負責在進程級別持有 LocationClient 並註冊監聽——這樣做的好處是定位對象的生命週期與應用一致,多個頁面可以共用同一個客戶端,不必反覆開銷初始化。

package com.genwoxue.baidulocation;

import com.baidu.location.*;

import android.app.Application;
import android.widget.TextView;
import android.os.Vibrator;

public class Location extends Application {

    public LocationClient mLocationClient = null;
    private String mData;
    public MyLocationListenner myListener = new MyLocationListenner();
    public TextView mTv;
    public NotifyLister mNotifyer = null;
    public Vibrator mVibrator01;
    public static String TAG = "LocTestDemo";

    @Override
    public void onCreate() {
        mLocationClient = new LocationClient(this);
        mLocationClient.registerLocationListener(myListener);
        super.onCreate();
    }

    public void logMsg(String str) {
        try {
            mData = str;
            if (mTv != null) {
                mTv.setText(mData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 監聽回調:收到新位置後格式化輸出到屏幕
     */
    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null) {
                return;
            }
            StringBuffer sb = new StringBuffer(256);
            sb.append("\nlatitude : ").append(location.getLatitude());
            sb.append("\nlontitude : ").append(location.getLongitude());
            sb.append("\nradius : ").append(location.getRadius());
            logMsg(sb.toString());
        }

        public void onReceivePoi(BDLocation poiLocation) {
            if (poiLocation == null) {
                return;
            }
            StringBuffer sb = new StringBuffer(256);
            sb.append("\nlatitude : ").append(poiLocation.getLatitude());
            sb.append("\nlontitude : ").append(poiLocation.getLongitude());
            sb.append("\nradius : ").append(poiLocation.getRadius());
        }
    }

    public class NotifyLister extends BDNotifyListener {
        public void onNotify(BDLocation mlocation, float distance) {
            mVibrator01.vibrate(1000);
        }
    }
}

BDLocationListener 的 onReceiveLocation 是整個定位的落點:SDK 每拿到一次新坐標就回調一次,我們從中取出經度、緯度和精度半徑。需要注意的是,這個回調工作在 SDK 的後台線程,若要直接刷新 UI 需自行切回主線程。

2. MainActivity.java:控制定位的開始與停止

package com.genwoxue.baidulocation;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

import android.app.Activity;
import android.app.Service;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    private TextView mTv = null;
    private Button btnStart;
    private Button btnStop;
    private Vibrator mVibrator01 = null;
    private LocationClient mLocClient;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTv = (TextView) findViewById(R.id.textview);
        btnStart = (Button) findViewById(R.id.start);
        btnStop = (Button) findViewById(R.id.stop);

        // 直接取用 Application 中已創建好的客戶端
        mLocClient = ((Location) getApplication()).mLocationClient;
        ((Location) getApplication()).mTv = mTv;
        mVibrator01 = (Vibrator) getApplication().getSystemService(Service.VIBRATOR_SERVICE);
        ((Location) getApplication()).mVibrator01 = mVibrator01;

        // 開始定位
        btnStart.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setLocationOption();
                mLocClient.start();
            }
        });

        // 停止定位
        btnStop.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mLocClient.stop();
            }
        });
    }

    // 設置定位參數
    private void setLocationOption() {
        LocationClientOption option = new LocationClientOption();
        option.setCoorType("bd09ll");
        mLocClient.setLocOption(option);
    }

    @Override
    public void onDestroy() {
        mLocClient.stop();
        ((Location) getApplication()).mTv = null;
        super.onDestroy();
    }
}

setCoorType("bd09ll") 指定使用百度自有的 BD-09 經緯度座標系。這一點在後續疊加地圖時很關鍵:如果拿 BD-09 的坐標去餵一張 WGS-84 或 GCJ-02 的底圖,會出現幾十到上百米的偏移。

四、配置文件

打開 AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.genwoxue.baidulocation" android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="15" />

    <application android:name="com.genwoxue.baidulocation.Location"
        android:label="@string/app_name">

        <activity android:name=".MainActivity"
            android:configChanges="orientation|keyboardHidden"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name="com.baidu.location.f" android:enabled="true"
            android:process=":remote">
        </service>

    </application>

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <uses-permission android:name="android.permission.READ_LOGS" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
</manifest>

兩處配置務必留意:

其一,Location.java 繼承自 Application,因此 <application> 節點必須加上 android:name,值為「包名 + 類名」,即 com.genwoxue.baidulocation.Location。漏掉這一句,自定義 Application 根本不會被實例化,定位客戶端也就無從創建。

其二,<service android:name="com.baidu.location.f" ... /> 來自百度定位 SDK 內部,內容不可改動,否則定位服務無法啟動。

另外,在 Android 6.0 及以上的系統上,ACCESS_FINE_LOCATION 這類危險權限還需要在運行時動態申請,僅在 Manifest 中聲明是不夠的。

五、運行結果

點擊開始定位後,屏幕上便會顯示當前的經度、緯度與精度半徑。

下一步

拿到經緯度只是上半場。把這組坐標交給上一章《百度地圖》裡的 MapView,讓地圖中心移動到當前位置,再疊一個定位圖層上去,「我在哪」才算真正閉環——而這一步,不過是幾行代碼的事。

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