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

取得定位經緯度並轉換為地址:LocationManager 完整實作

編輯:關於 Android 程式設計

Android 中取得裝置位置主要靠 LocationManager。本文示範如何取得經緯度、如何持續監聽位置變化,並進一步用地理編碼服務把座標轉成人看得懂的地址。

版面配置

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/positionView" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> 

基本版本:只取經緯度

 package com.example.testlocation; import java.util.List; import android.app.Activity; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.view.Menu; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private TextView postionView; private LocationManager locationManager; private String locationProvider; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //獲取顯示地理位置信息的TextView postionView = (TextView) findViewById(R.id.positionView); //獲取地理位置管理器 locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); //獲取所有可用的位置提供器 List<String> providers = locationManager.getProviders(true); if(providers.contains(LocationManager.GPS_PROVIDER)){ //如果是GPS locationProvider = LocationManager.GPS_PROVIDER; }else if(providers.contains(LocationManager.NETWORK_PROVIDER)){ //如果是Network locationProvider = LocationManager.NETWORK_PROVIDER; }else{ Toast.makeText(this, "沒有可用的位置提供器", Toast.LENGTH_SHORT).show(); return ; } //獲取Location Location location = locationManager.getLastKnownLocation(locationProvider); if(location!=null){ //不為空,顯示地理位置經緯度 showLocation(location); } //監視地理位置變化 locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener); } /** * 顯示地理位置經度和緯度信息 * @param location */ private void showLocation(Location location){ String locationStr = "維度:" + location.getLatitude() +"\n" + "經度:" + location.getLongitude(); postionView.setText(locationStr); } /** * LocationListern監聽器 * 參數:地理位置提供器、監聽位置變化的時間間隔、位置變化的距離間隔、LocationListener監聽器 */ LocationListener locationListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle arg2) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(Location location) { //如果位置發生變化,重新顯示 showLocation(location); } }; @Override protected void onDestroy() { super.onDestroy(); if(locationManager!=null){ //移除監聽器 locationManager.removeUpdates(locationListener); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }

流程拆解

1. 取得 LocationManager。用 getSystemService(Context.LOCATION_SERVICE)。

2. 選擇定位來源。有 GPS_PROVIDER、NETWORK_PROVIDER、PASSIVE_PROVIDER 三種,前兩者最常用。實務上優先 GPS(精度高但耗電、室內易失敗),GPS 不可用時退回網路定位。上面的程式碼用 getProviders(true) 只取「目前真的可用」的來源,這比判斷有沒有註冊來得準確。

3. 取最後已知位置。把來源傳給 getLastKnownLocation() 即可拿到 Location。注意它可能回傳 null(裝置剛開機、從未定位過),一定要判空。

4. 持續更新。呼叫 requestLocationUpdates(provider, minTime, minDistance, listener):第二個參數是時間間隔(毫秒),第三個是距離間隔(公尺),第四個是監聽器。上面的例子設 3 秒/1 公尺,算是相當激進的設定。

5. 位置變化時會回呼 onLocationChanged()。

6. 記得移除。在 onDestroy 中呼叫 removeUpdates()。這不只省電,更是必要的——否則 listener 被 LocationManager 持有,Activity 永遠無法回收,直接造成記憶體洩漏。

權限

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

若目標 SDK 為 23 以上,這兩個屬於危險權限,除了宣告還必須在執行期動態向使用者請求,只寫在 Manifest 會直接拿不到位置。

模擬器測試

在 DDMS 或模擬器控制面板送出座標即可觸發:

進階:把座標轉成地址

經緯度對使用者沒意義,要轉成地址就得呼叫地理編碼服務。因為涉及網路請求,必須放在背景執行緒,再用 Handler 回主執行緒更新 UI:

 package com.example.testlocation; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONObject; import android.app.Activity; import android.content.Context; 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.view.Menu; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private TextView postionView; private LocationManager locationManager; private String locationProvider; public static final int SHOW_LOCATION = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //獲取顯示地理位置信息的TextView postionView = (TextView) findViewById(R.id.positionView); //獲取地理位置管理器 locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); //獲取所有可用的位置提供器 List<String> providers = locationManager.getProviders(true); if(providers.contains(LocationManager.GPS_PROVIDER)){ //如果是GPS locationProvider = LocationManager.GPS_PROVIDER; }else if(providers.contains(LocationManager.NETWORK_PROVIDER)){ //如果是Network locationProvider = LocationManager.NETWORK_PROVIDER; }else{ Toast.makeText(this, "沒有可用的位置提供器", Toast.LENGTH_SHORT).show(); return ; } //獲取Location Location location = locationManager.getLastKnownLocation(locationProvider); if(location!=null){ //不為空,顯示地理位置經緯度 showLocation(location); }else{ Toast.makeText(this, "location為空", Toast.LENGTH_SHORT).show(); } //監視地理位置變化 locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener); } private Handler handler = new Handler(){ public void handleMessage(Message msg){ switch(msg.what){ case SHOW_LOCATION: String position = (String) msg.obj; postionView.setText(position); break; default: break; } } }; /** * 顯示地理位置經度和緯度信息 * @param location */ private void showLocation(final Location location){ /*String locationStr = "維度:" + location.getLatitude() +"\n" + "經度:" + location.getLongitude(); postionView.setText(locationStr);*/ new Thread(new Runnable() { @Override public void run() { try{ //組裝反向地理編碼的接口位置 StringBuilder url = new StringBuilder(); url.append("https://maps.googleapis.com/maps/api/geocode/json?latlng="); url.append(location.getLatitude()).append(","); url.append(location.getLongitude()); url.append("&sensor=false"); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url.toString()); httpGet.addHeader("Accept-Language","zh-CN"); HttpResponse response = client.execute(httpGet); if(response.getStatusLine().getStatusCode() == 200){ HttpEntity entity = response.getEntity(); String res = EntityUtils.toString(entity); //解析 JSONObject jsonObject = new JSONObject(res); //獲取results節點下的位置信息 JSONArray resultArray = jsonObject.getJSONArray("results"); if(resultArray.length() > 0){ JSONObject obj = resultArray.getJSONObject(0); //取出格式化後的位置數據 String address = obj.getString("formatted_address"); Message msg = new Message(); msg.what = SHOW_LOCATION; msg.obj = address; handler.sendMessage(msg); } } }catch(Exception e){ e.printStackTrace(); } } }).start(); } /** * LocationListern監聽器 * 參數:地理位置提供器、監聽位置變化的時間間隔、位置變化的距離間隔、LocationListener監聽器 */ LocationListener locationListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle arg2) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(Location location) { //如果位置發生變化,重新顯示 showLocation(location); } }; @Override protected void onDestroy() { super.onDestroy(); if(locationManager!=null){ //移除監聽器 locationManager.removeUpdates(locationListener); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }

記得加上網路權限:

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

實務上的幾點提醒

位置更新太頻繁會同時觸發大量網路請求,實作時應加上節流——例如「移動超過 100 公尺才重新查地址」,否則使用者搭車時會發現流量與電量都被吃光。另外,若主要目標只是「偶爾取一次座標」,改用 FusedLocationProviderClient(Google Play 服務)會更省電,它會自動權衡 GPS 與網路定位的取捨;上面的 LocationManager 寫法在沒有 Google 服務的裝置上反而更可靠,可依目標市場挑選。

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