歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android GPS定位系統

Android GPS定位系統

日期:2017/3/1 10:23:53   编辑:Linux編程

GPS(Gobal Positional System)全球定位系統,是一個中距離圓型軌道衛星導航系統,他可以為地球表面的絕大部分地區(98%)提供准備的定位、測速和高精度的時間標准。

Android支持地理定位服務的API。該地理定位服務可以用來獲取當前設備的地理位置,應用程序可以定時請求更新設備當前的地理定位信息。比如應用程序可以借助一個Intent接受器來實現如下功能:以經緯度和半徑劃定一個區域,當設備出入該區域時,發出提示信息,還可以和Google Map API一起使用,完成更多的任務。關於地理定位系統的API全部位於android.location包內,其中包括以下幾個重要的功能類:

類名

描述

LocationManager

提供訪問定位服務的功能,也提供獲取最佳定位提供者的功能,另外,臨時報警功能也可以借助該類來實現。

LocationProvider

定位提供者的抽象類。定位提供者具備周期性報告設備地理位置的功能。

LocationListener

提供定位信息發生改變時的回調共嫩。必須事先在定位管理器中注冊監聽器對象。

Criteria

使得應用能夠通過LocationProvider中設置的屬性來選擇合適的定位提供者。

Geocoder

用於處理地理編碼和反向地理編碼的類。地理編碼是指將地址或其他描述轉變為經度和緯度,反向地理編碼則是將經度和緯度轉變為地址或描述語言,其中包含了兩個構造函數,需要傳入經度和緯度的坐標。getFromLocation方法可以得到一組關於地址的數組。

要使用地理定位,首先需要取得LocationManager的實例,在Android中,獲得LocationManager的唯一方法是通過getSystemService方法的調用。通過使用LocationManager,我們可以獲得一個位置提供者的列表。在一個真實的手持設備中,這個列表包含了一些GPS服務。我們也可以選擇更強大、更精確、不帶其他附加服務的GPS。代碼如下:

LocationManager locationManager;

Stringcontext = Context.LOCATION_SERVICE;

locationManager= (LocationManager)getSystemService(context);

取得LocationManager對象之後,我們還需要注冊一個周期的更新視圖,代碼如下

LocationManager.requestLocationUpdate(LocationManager.GPS_PROVDER,1000, 0, locationListener);

其中第一個參數是設置服務提供者,第二個參數是周期,最後一個參數locationListener,是用來監聽定位信息的改變,必須要實現如下方法:

方法

描述

onLocationChanged(Location location)

當坐標改變時候觸發該函數,如果Provider傳相同的坐標,它就不會觸發。

onProviderDisabled(String provider)

Provider禁用時觸發此函數,比如GPS被關閉。

onProviderEnabled(String provider)

Provider啟用時觸發此函數,比如GPS被打開。

onStatusChanged(String provider, int status, Bundle extras)

Provider的轉態在可用、暫時不可用和無服務三個狀態直接切換時觸發此函數。

要使用定位的API,首先需要再AndroidManifest.xml文件中添加其權限,具體代碼如下:

  1. <uses-permission android:name="android.permission.INTERNET"/>
  2. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  3. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  4. <application
  5. android:icon="@drawable/ic_launcher"
  6. android:label="@string/app_name" >
  7. <uses-library android:name="com.google.android.maps"/>
  8. <activity
  9. android:name=".GPSActivity"
  10. android:label="@string/app_name" >

由於我們在模擬器上測試,所以需要人為的設置一個坐標。可用通過兩種方法來設置一個模擬的坐標值。第一種方法是通過DDMS,我們可用在Eclipse的ADT插件中使用這種方法,只要啟動Eclipse,選擇“Window”->“Show View”,打開“Emulator Control”界面手動或者通過KML和GPX文件來設置一個坐標。

另外一種方法使用geo命令,我們需要telnet到本機的5554端口,然後再命令行下輸入類似於geo fix-121.45365 46.51119 4392這樣的命令,後面三個參數分別是經度、緯度和(可選)海拔。設置後再Android模擬器屏幕上便多出了一個如圖9-17所示的標准,表示模擬了一個GPS權限。

現在我們可以使用位置管理器(LocationManager)和位置提供者進行getFromLocation的調用。這個方法放回本機當前位置的一個快照,這個快照將以Location對象形式提供。在手持設備中,我們可以獲得當前位置的經度和緯度;調用getFromLocationName方法可以返回一個數據表示一個地方的地名。

在這個地圖中,我們還可以創建了一個菜單來縮放地圖,這個功能是使用地圖控制器(MapController)的zoomIn和zoomOut方法來放大和縮小地圖。

下面試測試一個示例代碼:

  1. package cn.edu.pku;
  2. import java.io.IOException;
  3. import java.util.List;
  4. import java.util.Locale;
  5. import com.google.android.maps.GeoPoint;
  6. import com.google.android.maps.MapActivity;
  7. import com.google.android.maps.MapController;
  8. import com.google.android.maps.MapView;
  9. import com.google.android.maps.Overlay;
  10. import android.content.Context;
  11. import android.graphics.Bitmap;
  12. import android.graphics.BitmapFactory;
  13. import android.graphics.Canvas;
  14. import android.graphics.Paint;
  15. import android.graphics.Point;
  16. import android.location.Address;
  17. import android.location.Criteria;
  18. import android.location.Geocoder;
  19. import android.location.Location;
  20. import android.location.LocationListener;
  21. import android.location.LocationManager;
  22. import android.os.Bundle;
  23. import android.view.Menu;
  24. import android.view.MenuItem;
  25. import android.widget.TextView;
  26. public class GPSActivity extends MapActivity {
  27. public MapController mapController;
  28. public MyLocationOverlay myPosition;
  29. public MapView myMapView;
  30. public static final int ZOOM_IN = Menu.FIRST;
  31. public static final int ZOOM_OUT = Menu.FIRST + 1;
  32. @Override
  33. protected void onCreate(Bundle icicle) {
  34. // TODO Auto-generated method stub
  35. super.onCreate(icicle);
  36. setContentView(R.layout.main);
  37. LocationManager locationManager;
  38. String context = Context.LOCATION_SERVICE;
  39. locationManager = (LocationManager)getSystemService(context);
  40. myMapView = (MapView)findViewById(R.id.mapView1);
  41. mapController = myMapView.getController();
  42. //設置顯示模式
  43. myMapView.setSatellite(true);
  44. myMapView.setStreetView(true);
  45. //設置縮放控制,這裡使用自己實現的縮放菜單
  46. myMapView.displayZoomControls(false);
  47. //設置使用MyLocationOverlay繪圖
  48. mapController.setZoom(17);
  49. myPosition = new MyLocationOverlay();
  50. List<Overlay> overlays = myMapView.getOverlays();
  51. overlays.add(myPosition);
  52. //設置Criteria(服務商)的信息
  53. Criteria criteria = new Criteria();
  54. //經度要求
  55. criteria.setAccuracy(Criteria.ACCURACY_FINE);
  56. criteria.setAltitudeRequired(false);
  57. criteria.setBearingRequired(false);
  58. criteria.setCostAllowed(false);
  59. criteria.setPowerRequirement(Criteria.POWER_LOW);
  60. //取得最好效果的criteria
  61. String provider = locationManager.getBestProvider(criteria, true);
  62. //獲得坐標相應信息
  63. Location location = locationManager.getLastKnownLocation(provider);
  64. //更新坐標相關信息
  65. updateWithNewLocation(location);
  66. //注冊一個周期的更新,3000ms更新一次
  67. //locationManager用來監聽定位信息的改變
  68. locationManager.requestLocationUpdates(provider, 3000, 0, locationListener);
  69. }
  70. private void updateWithNewLocation(Location location){
  71. String latLongString;
  72. TextView myLocationText = (TextView)findViewById(R.id.textView1);
  73. String addressString = "沒有找到地址\n";
  74. if(location != null){
  75. //為繪制標志的類設置坐標
  76. //myPosition.
  77. //取得經度和緯度
  78. Double geoLat = location.getLatitude() * 1E6;
  79. Double geoLng = location.getLongitude() * 1E6;
  80. GeoPoint point = new GeoPoint(geoLat.intValue(), geoLng.intValue());
  81. //定位到指定坐標
  82. mapController.animateTo(point);
  83. double lat = location.getLatitude();
  84. double lng = location.getLongitude();
  85. latLongString = "經度:" + lat + "\n緯度:" + lng;
  86. double latitude = location.getLatitude();
  87. double longitude = location.getLongitude();
  88. //根據地理環境來確定編碼
  89. Geocoder gc = new Geocoder(this, Locale.getDefault());
  90. try{
  91. //取得地址相關的一些信息、經度、緯度
  92. List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
  93. StringBuilder sb = new StringBuilder();
  94. if(addresses.size() > 0){
  95. Address address = addresses.get(0);
  96. for(int i = 0; i < address.getMaxAddressLineIndex(); i++){
  97. sb.append(address.getAddressLine(i)).append("\n");
  98. sb.append(address.getLocality()).append("\n");
  99. sb.append(address.getPostalCode()).append("\n");
  100. sb.append(address.getCountryName());
  101. addressString = sb.toString();
  102. }
  103. }
  104. }catch(IOException e){}
  105. }else{
  106. latLongString = "沒有找到坐標. \n";
  107. }
  108. myLocationText.setText("你當前的坐標如下:\n" + latLongString + "\n" + addressString);
  109. }
  110. private final LocationListener locationListener = new LocationListener() {
  111. public void onStatusChanged(String provider, int status, Bundle extras) {//Provider轉態在可用、暫時不可服務和無服務三個狀態直接切換時觸發此函數
  112. // TODO Auto-generated method stub
  113. }
  114. public void onProviderEnabled(String provider) {//Provider啟用時觸發此函數,比如GPS被打開
  115. // TODO Auto-generated method stub
  116. }
  117. public void onProviderDisabled(String provider) {//Provider禁用時觸發此函數,比如GPS被關閉
  118. // TODO Auto-generated method stub
  119. updateWithNewLocation(null);
  120. }
  121. public void onLocationChanged(Location location) {//當坐標改變時觸發事件
  122. // TODO Auto-generated method stub
  123. updateWithNewLocation(location);
  124. }
  125. };
  126. @Override
  127. protected boolean isRouteDisplayed() {
  128. // TODO Auto-generated method stub
  129. return false;
  130. }
  131. @Override
  132. public boolean onOptionsItemSelected(MenuItem item) {
  133. // TODO Auto-generated method stub
  134. super.onOptionsItemSelected(item);
  135. switch(item.getItemId()){
  136. case ZOOM_IN:
  137. mapController.zoomIn();
  138. return true;
  139. case ZOOM_OUT:
  140. mapController.zoomOut();
  141. return true;
  142. }
  143. return true;
  144. }
  145. @Override
  146. public boolean onCreateOptionsMenu(Menu menu) {
  147. // TODO Auto-generated method stub
  148. super.onCreateOptionsMenu(menu);
  149. menu.add(0, ZOOM_IN, Menu.NONE, "放大");
  150. menu.add(0, ZOOM_OUT, Menu.NONE, "縮小");
  151. return true;
  152. }
  153. class MyLocationOverlay extends Overlay{
  154. Location mLocation;
  155. //更新坐標時,設置該坐標,以便畫圖
  156. public void setLocation(Location location){
  157. mLocation = location;
  158. }
  159. @Override
  160. public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
  161. long when) {
  162. // TODO Auto-generated method stub
  163. super.draw(canvas, mapView, shadow, when);
  164. Paint paint = new Paint();
  165. Point myScreenCoords = new Point();
  166. //將經緯度轉換成實際屏幕坐標
  167. GeoPoint tmpGeoPoint = new GeoPoint((int)(mLocation.getLatitude() * 1E6), (int)(mLocation.getLongitude() * 1E6));
  168. mapView.getProjection().toPixels(tmpGeoPoint, myScreenCoords);
  169. paint.setStrokeWidth(1);
  170. paint.setARGB(255, 255, 0, 0);
  171. paint.setStyle(Paint.Style.STROKE);
  172. Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.home);
  173. canvas.drawBitmap(bmp, myScreenCoords.x, myScreenCoords.y, paint);
  174. canvas.drawText("Here am I", myScreenCoords.x, myScreenCoords.y, paint);
  175. return true;
  176. }
  177. }
  178. }

運行效果:



注意:Loction常常獲取null,在網上查了很多資料。發現最主要是我們不能查到那個GPS提供商的能提供定位,有用while循環知道獲取停止,但是這個時間可能等待很長的時間都不能獲取到,我是采用下面的

  1. String provider = locationManager.getBestProvider(criteria, true);
  2. List<String> privatelist= locationManager.getAllProviders();
  3. for(String privates:privatelist)
  4. {
  5. Location locat=locationManager.getLastKnownLocation(privates);
  6. if(locat!=null)
  7. {
  8. provider=privates;
  9. break;
  10. }
  11. }
  12. //獲得坐標相應信息
  13. Location location = locationManager.getLastKnownLocation(provider);

這樣可以檢測到,但是這個不是最優的方法,但是可以得到運行的效果。

Copyright © Linux教程網 All Rights Reserved