歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android獲取經緯度:從谷歌源碼中提取出來的獲取經緯度代碼

Android獲取經緯度:從谷歌源碼中提取出來的獲取經緯度代碼

日期:2017/3/1 11:10:30   编辑:Linux編程

經過測試發現,在有的手機上獲取經緯度沒有問題,在其他的手機上獲取經緯度卻又問題,因此我查看了谷歌提供的源碼,從源碼裡面提取出了一份新的獲取經緯度的代碼,以後每次獲取基本都獲取成功了:

  1. LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
  2. Location retLocation = null ;
  3. LocationProvider gpsProvider =
  4. lm.getProvider("gps");
  5. if(gpsProvider == null)
  6. {
  7. longitude.setText("0");
  8. dimensions.setText("0");
  9. return;
  10. }
  11. //下面必須原封不動的照搬,否則就會出錯,原因我也不知道。
  12. lm.requestLocationUpdates(gpsProvider.getName(),
  13. 0 /*minTime*/, 0 /*minDist*/, this);
  14. try {
  15. lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
  16. 3000 /*minTime*/, 0 /*minDist*/, this);
  17. } catch (RuntimeException e) {
  18. // If anything at all goes wrong with getting a cell location do not
  19. // abort. Cell location is not essential to this app.
  20. }
  21. retLocation = lm.getLastKnownLocation("gps");
  22. if(retLocation==null)
  23. {
  24. longitude.setText("0");
  25. dimensions.setText("0");
  26. }
  27. else
  28. {
  29. double geoLatitude = retLocation.getLatitude();//獲取經度
  30. double geoLongitude = retLocation.getLongitude();//獲取維度
  31. longitude.setText(""+geoLongitude);
  32. dimensions.setTag(""+geoLatitude);
  33. }
  34. longitude.setEnabled(false);
  35. Location改變的消息在這個接口方法中獲取:
  36. private void updataGpsWidthLocation(Location location) {
  37. // TODO Auto-generated method stub
  38. if(location != null)
  39. {
  40. double lit = location.getLongitude();//進度
  41. double dimen = location.getLatitude();//維度
  42. longitude.setText(""+lit);
  43. this.dimensions.setText(""+dimen);
  44. float accuray=location.getAccuracy();//獲取精確度
  45. Log.e("", "accuray:"+accuray);
  46. accurText.setText(""+accuray);
  47. }
  48. else
  49. {
  50. longitude.setText("0");
  51. dimensions.setText("0");
  52. }
  53. }
Copyright © Linux教程網 All Rights Reserved