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

Android 自動切換網絡與 GPS 定位

編輯:關於 Android 程式設計

Android 自動切換網絡與 GPS 定位

思路是:獲取位置服務後,同時向網絡和 GPS 兩個 provider 請求定位更新,這樣系統會同時上報兩路的位置信息。沒有 GPS 信號時自動採用網絡定位,有 GPS 信號時則優先使用 GPS 提供的位置。核心在於 isBetterLocation() 方法——它綜合時間、精度、定位方式等因素判斷新位置是否更優,決定是否更新當前位置,這個方法源自官方開發指南的 "Obtaining User Location"。

關鍵代碼

在 onResume 中同時向兩個 provider 註冊監聽,在 onPause 中註銷:

@Override
protected void onResume() {
    super.onResume();
    lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
}

@Override
protected void onPause() {
    super.onPause();
    lm.removeUpdates(listener);
}

在 onLocationChanged 回調中,用 isBetterLocation 過濾掉不理想的結果,再取出經緯度、provider、精度、海拔、方位角、速度等信息顯示:

LocationListener listener = new LocationListener() {
    public void onLocationChanged(Location location) {
        if (isBetterLocation(location, myLocation)) {
            double lat = location.getLatitude();
            double lon = location.getLongitude();
            String provider = location.getProvider();
            float accuracy = location.getAccuracy();
            double altitude = location.getAltitude();
            float bearing = location.getBearing();
            float speed = location.getSpeed();
            // 更新 myLocation 並刷新界面
        }
    }
    // onStatusChanged / onProviderEnabled / onProviderDisabled 略
};

判斷新位置是否更優的核心邏輯如下:

private static final int TWO_MINUTES = 1000 * 60 * 2;

protected boolean isBetterLocation(Location location, Location currentBestLocation) {
    if (currentBestLocation == null) {
        return true; // 沒有舊位置時,任何新位置都更好
    }
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;

    if (isSignificantlyNewer) {
        return true;               // 新位置明顯更新,用戶可能已移動
    } else if (isSignificantlyOlder) {
        return false;              // 新位置明顯更舊,直接丟棄
    }

    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 200;
    boolean isFromSameProvider = isSameProvider(
        location.getProvider(), currentBestLocation.getProvider());

    if (isMoreAccurate) {
        return true;
    } else if (isNewer && !isLessAccurate) {
        return true;
    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
        return true;
    }
    return false;
}

總體原則是:先看時間,時間差超過兩分鐘就直接採用新的;時間相近時再比精度,精度更高、或更新且精度沒有變差、或更新且精度沒有明顯變差並來自同一 provider 時,才採納新位置。

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