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

Android Service 結合 GPS 與基地台定位的實作

編輯:關於 Android 程式設計

需求說明

本實例希望 Service 每隔 1 秒執行一次定位,優先使用 GPS,若 GPS 無法取得位置,則改用基地台定位,最後將經緯度即時顯示在畫面上。

所需權限

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

核心思路

Gps 類別負責封裝 LocationManager,取得目前位置。GpsService 在背景執行,每秒取得經緯度;若 GPS 定位為空,則改以基地台資訊向網路服務查詢。最後透過廣播將 lat、lon 傳給 GpsActivity。

GpsService 核心程式

public class GpsService extends Service {
    private Gps gps = null;
    private boolean threadDisable = false;

    @Override
    public void onCreate() {
        super.onCreate();
        gps = new Gps(GpsService.this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (!threadDisable) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (gps != null) {
                        Location location = gps.getLocation();
                        if (location == null) {
                            try {
                                location = UtilTool.callGear(GpsService.this, UtilTool.init(GpsService.this));
                            } catch (Exception e) {
                                location = null;
                                e.printStackTrace();
                            }
                        }
                        Intent intent = new Intent();
                        intent.putExtra("lat", location == null ? "" : String.valueOf(location.getLatitude()));
                        intent.putExtra("lon", location == null ? "" : String.valueOf(location.getLongitude()));
                        intent.setAction("com.ljq.activity.GpsService");
                        sendBroadcast(intent);
                    }
                }
            }
        }).start();
    }

    @Override
    public void onDestroy() {
        threadDisable = true;
        if (gps != null) {
            gps.closeLocation();
            gps = null;
        }
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

Activity 顯示定位結果

GpsActivity 註冊廣播接收器,收到 lat 與 lon 後即可更新畫面。若需要計算距離,也可使用 Location.distanceBetween() 進行換算。

基地台定位通常依賴網路服務與電信資訊,實際部署時應確認相關服務是否仍可使用。

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