Android获取经纬度:从谷歌源码中提取出来的获取经纬度代码


经过测试发现,在有的手机上获取经纬度没有问题,在其他的手机上获取经纬度却又问题,因此我查看了谷歌提供的源码,从源码里面提取出了一份新的获取经纬度的代码,以后每次获取基本都获取成功了: 

  1. LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);  
  2.   
  3. Location retLocation = null ;  
  4. LocationProvider gpsProvider =  
  5. lm.getProvider("gps");  
  6.   
  7. if(gpsProvider == null)  
  8. {  
  9. longitude.setText("0");  
  10. dimensions.setText("0");  
  11. return;  
  12. }  
  13.   
  14.   
  15. //下面必须原封不动的照搬,否则就会出错,原因我也不知道。   
  16. lm.requestLocationUpdates(gpsProvider.getName(),  
  17. 0 /*minTime*/0 /*minDist*/this);  
  18. try {  
  19. lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,  
  20. 3000 /*minTime*/0 /*minDist*/this);  
  21. catch (RuntimeException e) {  
  22. // If anything at all goes wrong with getting a cell location do not   
  23. // abort. Cell location is not essential to this app.   
  24. }  
  25.   
  26. retLocation = lm.getLastKnownLocation("gps");  
  27. if(retLocation==null)  
  28. {  
  29. longitude.setText("0");  
  30. dimensions.setText("0");  
  31. }  
  32. else  
  33. {  
  34. double geoLatitude = retLocation.getLatitude();//获取经度   
  35. double geoLongitude = retLocation.getLongitude();//获取维度   
  36.   
  37. longitude.setText(""+geoLongitude);  
  38. dimensions.setTag(""+geoLatitude);  
  39. }  
  40.   
  41. longitude.setEnabled(false);  
  42.    
  43.   
  44. Location改变的消息在这个接口方法中获取:  
  45.   
  46.   
  47. private void updataGpsWidthLocation(Location location) {  
  48. // TODO Auto-generated method stub   
  49. if(location != null)  
  50. {  
  51. double lit = location.getLongitude();//进度   
  52. double dimen = location.getLatitude();//维度   
  53. longitude.setText(""+lit);  
  54. this.dimensions.setText(""+dimen);  
  55. float accuray=location.getAccuracy();//获取精确度   
  56. Log.e("""accuray:"+accuray);  
  57. accurText.setText(""+accuray);  
  58. }  
  59. else  
  60. {  
  61. longitude.setText("0");  
  62. dimensions.setText("0");  
  63. }  
  64. }  

相关内容