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

Android GPS 定位用法實例:LocationManager 與 LocationListener 完整示範

編輯:Android 開發實例

GPS 定位是手機上非常實用的能力。本文以實例說明在 Android 中如何透過 GPS 取得當前經緯度,並即時顯示在畫面上。

基本觀念

在 Android 中取得位置,第一步是取得 LocationManager 實例。它可以透過兩種主要方式取得位置:

· getLastKnownLocation(provider)——取得最後一次已知位置,這是快取值,回來得快但不保證新鮮

· requestLocationUpdates(...)——註冊持續的位置更新,參數依次為定位方式、更新間隔(毫秒)、距離間隔(公尺)、監聽器

provider 可選 LocationManager.GPS_PROVIDER(純 GPS,精度高但耗電、室內無效)或 LocationManager.NETWORK_PROVIDER(基地台與 WiFi,精度較低但室內可用)。本文示範 GPS。listener 則是自行實作的 LocationListener,在其中覆寫 onLocationChanged() 加入位置變化時的處理。

版面配置

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
   xmlns:tools="https://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" >

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

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

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

MainActivity

 package com.hzhi.my_gps;

 import java.text.SimpleDateFormat;
 import java.util.Date;
 import java.util.Timer;
 import java.util.TimerTask;
 import android.location.Criteria;
 import android.location.Location;
 import android.location.LocationListener;
 import android.location.LocationManager;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Message;
 import android.app.Activity;
 import android.content.Context;
 import android.view.Menu;
 import android.widget.TextView;

 public class MainActivity extends Activity {
   TextView txt_time;
   TextView txt_lat;
   TextView txt_lng;
   LocationManager lom;
   Location loc;
   Double lat;
   Double lng;
   SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   Date now;
   String str_date;
   Timer timer;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     get_con();
     get_gps();
     timer = new Timer(true);
     timer.schedule(task, 0, 1000);
   }

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
     getMenuInflater().inflate(R.menu.main, menu);
     return true;
   }

   public void get_gps(){
     lom = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
     loc = lom.getLastKnownLocation(LocationManager.GPS_PROVIDER);
     if (loc != null) {
       lat = loc.getLatitude();
       lng = loc.getLongitude();
       txt_lat.setText("緯度:" + String.valueOf(lat));
       txt_lng.setText("經度:" + String.valueOf(lng));
     } else{
       txt_lat.setText("緯度:未知");
       txt_lng.setText("經度:未知");
     }

     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 = lom.getBestProvider(criteria, true);
     lom.requestLocationUpdates(provider, 1000, 10, los);
   }

   LocationListener los = new LocationListener(){
     public void onLocationChanged(Location location){
       if (location != null) {
         lat = location.getLatitude();
         lng = location.getLongitude();
         txt_lat.setText("緯度:" + String.valueOf(lat));
         txt_lng.setText("經度:" + String.valueOf(lng));
       } else{
         txt_lat.setText("緯度:未知");
         txt_lng.setText("經度:未知");
       }
     };
     public void onProviderDisabled(String provider){ };
     public void onProviderEnabled(String provider){ };
     public void onStatusChanged(String provider, int status, Bundle extras){ };
   };

   // 獲取控件
   public void get_con(){
     txt_time = (TextView) findViewById(R.id.txt_time);
     txt_lat = (TextView) findViewById(R.id.txt_lat);
     txt_lng = (TextView) findViewById(R.id.txt_lng);
   }

   Handler handler = new Handler(){
     public void handleMessage(Message msg){
       switch (msg.what){
         case 1:
           get_time();
           break;
       }
     }
   };

   TimerTask task = new TimerTask(){
     public void run() {
       Message message = new Message();
       message.what = 1;
       handler.sendMessage(message);
     }
   };

   // 獲取時間
   public void get_time(){
     now = new Date(System.currentTimeMillis());
     str_date = formatter.format(now);
     txt_time.setText("時間:" + str_date);
   }
 }

在 AndroidManifest.xml 中加入權限:

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

運行前請先開啟 GPS 衛星定位,運行結果如下:

讀者可以在室外信號充足的地方試試,確實能取到 GPS 位置。

程式碼中的幾個問題與改良建議

這份程式碼把整個流程示範得很清楚,但仍有幾處會在真机上造成困擾,值得逐一說明。

1. 經緯度標籤寫反了。版面配置中 txt_lat 的預設文字是「經度」,txt_lng 是「緯度」,但程式碼中 lat(getLatitude())寫進 txt_lat,lng 寫進 txt_lng。程式碼的赋值是對的,錯的是 XML 的預設文字,會讓畫面標示顛倒。

2. Timer 每秒刷新時間是多餘的。用 Timer + Handler 每秒更新一次時間標籤,既耗電又增加複雜度。時間只在需要顯示時取一次即可;若真要即時時鐘,用 TextClock 或 Chronometer 這類現成控制項,框架會自行處理。

3. 一定要在 onPause 中停止更新。程式碼沒有呼叫 requestLocationUpdates 的解除,離開畫面後 GPS 仍持續開著,是嚴重的電力浪費。正確做法是在 onPause() 或 onStop() 中呼叫 lom.removeUpdates(los),回到前台時再重新註冊。

4. 動態權限。ACCESS_FINE_LOCATION 自 Android 6.0 起屬危險權限,僅在 Manifest 宣告會導致 SecurityException。必須用 requestPermissions() 執行期請求,並處理結果回呼。

5. Criteria 已不再推薦。getBestProvider(criteria, true) 是舊寫法。目前官方建議使用 FusedLocationProviderClient(Google Play 服務的一部分),它會智慧地混合 GPS、WiFi 與基地台,在精度、耗電與可用性之間自動取捨,也能免費取得室內定位能力。

6. GPS 首次定位可能很久。冷啟動時 GPS 需要下載星曆,室外可能等 30 秒到數分鐘。良好的使用者體驗是先用網路定位墊畫面,等 GPS 精度提升後再更新,同時顯示「定位中」的提示。

把上述幾點補上,這個定位功能就能平穩地在正式環境運行。希望本文所述對大家的 Android 開發有所幫助。

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