Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android GPS 定位實作:把經緯度即時顯示在畫面上

上一篇文章拆解了定位 API 的結構,這次把它做成一個能跑的小程式:畫面上兩個 TextView,一個顯示目前位置資訊,一個顯示 GPS 的狀態。

前置作業:權限

要在真機取得精確座標,必須在清單中宣告 ACCESS_FINE_LOCATION 權限,只用網路定位的話則是 ACCESS_COARSE_LOCATION。缺少權限時 getSystemService 拿到的物件不會出錯,但永遠不會有座標回來,這是初學者最常踩的坑。

介面:純程式化建立

版面用一個垂直的 LinearLayout 當根節點,依序放入 infoView 與 locationView 兩個 TextView,不需要任何 XML:

mainView = new LinearLayout(this);
mainView.setOrientation(LinearLayout.VERTICAL);
infoView = new TextView(this);
mainView.addView(infoView);
locationView = new TextView(this);
mainView.addView(locationView);
setContentView(mainView);

初始化流程分兩層

locationManager_init 負責取得 LocationManager、呼叫監聽器的初始化,然後 requestLocationUpdates(GPS_PROVIDER, 1000, 0, locationListener),也就是每 1000 毫秒、位移不設門檻地更新。locationListener_init 則建立匿名 LocationListener,實作四個回呼:

  • onLocationChanged:把時間、經度、緯度、海拔逐一 append 到 locationView。
  • onProviderDisabled:infoView 顯示「當前 GPS 狀態:禁用」。
  • onProviderEnabled:infoView 顯示「當前 GPS 狀態:開啟」。
  • onStatusChanged:依 AVAILABLE、OUT_OF_SERVICE、TEMPORARILY_UNAVAILABLE 顯示「可見的」、「服務區外」、「暫停服務」。
public void onLocationChanged(Location location) {
    locationView.setText("時間:" + location.getTime() + "\n");
    locationView.append("經度:" + location.getLongitude() + "\n");
    locationView.append("緯度:" + location.getLatitude() + "\n");
    locationView.append("海拔:" + location.getAltitude() + "\n");
}

實測時會遇到的狀況

室內或剛啟動時,GPS 往往處於搜尋狀態,畫面只會停在狀態文字上,這時走到窗邊或室外就會有座標。若一直停在「禁用」,代表使用者關閉了定位服務,此時可以導引他前往系統設定開啟。

另外,這個範例把更新週期設成 1 秒,耗電偏高;正式應用通常會拉長間隔、加上最小位移門檻,並在 Activity 的 onPause 中呼叫 removeUpdates 取消註冊,避免離開畫面後仍在背景消耗電力。

Copyright © Linux教程網 All Rights Reserved