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

Android 實現 GPS 定位的程式碼實作範例

編輯:關於 Android 程式設計

GPS 定位回傳的是一個 Location 物件,從中取出經緯度並轉成 double 即可使用,例如緯度 23.223871812820435、經度 113.58986039161628。本文示範一個最小可用的實作:畫面上一個文字區塊加上「定位」與「停止」兩個按鈕。

版面配置

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

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

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

宣告與事件綁定

Location 用來承載經緯度,LocationManager 則是系統的位置服務:

private Button btnStart;
private Button btnStop;
private TextView textView;
private Location mLocation;
private LocationManager mLocationManager;

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

    btnStart = (Button) findViewById(R.id.btnStart);
    btnStop = (Button) findViewById(R.id.btnStop);
    textView = (TextView) findViewById(R.id.text);

    btnStart.setOnClickListener(btnClickListener);   // 開始定位
    btnStop.setOnClickListener(btnClickListener);    // 停止定位
}

點擊事件的概念很直接:按下「定位」時先確認 GPS 是否開啟,再取得座標並顯示;按下「停止」則移除位置更新監聽。其中 mLocationManager.removeUpdates() 就是停止監聽的關鍵。

public Button.OnClickListener btnClickListener = new Button.OnClickListener() {
    public void onClick(View v) {
        Button btn = (Button) v;
        if (btn.getId() == R.id.btnStart) {
            if (!gpsIsOpen()) return;
            mLocation = getLocation();
            if (mLocation != null)
                textView.setText("緯度:" + mLocation.getLatitude() + "\n經度:" + mLocation.getLongitude());
            else
                textView.setText("獲取不到數據");
        } else if (btn.getId() == R.id.btnStop) {
            mLocationManager.removeUpdates(locationListener);
        }
    }
};

檢查 GPS 是否開啟

private boolean gpsIsOpen() {
    boolean bRet = true;
    LocationManager alm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    if (!alm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        Toast.makeText(this, "未開啟GPS", Toast.LENGTH_SHORT).show();
        bRet = false;
    } else {
        Toast.makeText(this, "GPS已開啟", Toast.LENGTH_SHORT).show();
    }
    return bRet;
}

取得目前座標

這裡有個實務上必須知道的特性:第一次呼叫 getLastKnownLocation() 往往會拿到 null,因為系統還沒有可用的快取值。真正的座標要等 LocationListener 回呼才會到來。

private Location getLocation() {
    // 取得位置管理服務
    mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    // 條件設定
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);      // 定位精度:最高
    criteria.setAltitudeRequired(false);             // 不需要海拔
    criteria.setBearingRequired(false);              // 不需要方位
    criteria.setCostAllowed(true);                   // 允許付費定位
    criteria.setPowerRequirement(Criteria.POWER_LOW);// 低功耗

    String provider = mLocationManager.getBestProvider(criteria, true);
    Location location = mLocationManager.getLastKnownLocation(provider);

    // 開啟監聽:最短間隔 2000 毫秒、最短位移 5 公尺
    mLocationManager.requestLocationUpdates(provider, 2000, 5, locationListener);
    return location;
}

等待座標變化

private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        if (location != null)
            textView.setText("緯度:" + location.getLatitude() + "\n經度:" + location.getLongitude());
        else
            textView.setText("獲取不到數據");
    }

    public void onProviderDisabled(String provider) { }
    public void onProviderEnabled(String provider) { }

    public void onStatusChanged(String provider, int status, Bundle extras) { }
};

別忘了權限

以上程式要能正常運作,必須在 AndroidManifest.xml 中宣告定位權限,否則 getSystemService 取得的服務不會回傳任何座標:

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

補充兩點實務經驗:requestLocationUpdates 一定要在 Activity 的 onPause 或 onStop 中搭配 removeUpdates 釋放,否則會持續耗電;另外 requestLocationUpdates 屬非同步回呼,UI 更新若要從其他線程觸發,記得切回主線程處理。

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