經過測試發現,在有的手機上獲取經緯度沒有問題,在其他的手機上獲取經緯度卻又問題,因此我查看了谷歌提供的源碼,從源碼裡面提取出了一份新的獲取經緯度的代碼,以後每次獲取基本都獲取成功了:
- LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
-
- Location retLocation = null ;
- LocationProvider gpsProvider =
- lm.getProvider("gps");
-
- if(gpsProvider == null)
- {
- longitude.setText("0");
- dimensions.setText("0");
- return;
- }
-
-
- //下面必須原封不動的照搬,否則就會出錯,原因我也不知道。
- lm.requestLocationUpdates(gpsProvider.getName(),
- 0 /*minTime*/, 0 /*minDist*/, this);
- try {
- lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
- 3000 /*minTime*/, 0 /*minDist*/, this);
- } catch (RuntimeException e) {
- // If anything at all goes wrong with getting a cell location do not
- // abort. Cell location is not essential to this app.
- }
-
- retLocation = lm.getLastKnownLocation("gps");
- if(retLocation==null)
- {
- longitude.setText("0");
- dimensions.setText("0");
- }
- else
- {
- double geoLatitude = retLocation.getLatitude();//獲取經度
- double geoLongitude = retLocation.getLongitude();//獲取維度
-
- longitude.setText(""+geoLongitude);
- dimensions.setTag(""+geoLatitude);
- }
-
- longitude.setEnabled(false);
-
-
- Location改變的消息在這個接口方法中獲取:
-
-
- private void updataGpsWidthLocation(Location location) {
- // TODO Auto-generated method stub
- if(location != null)
- {
- double lit = location.getLongitude();//進度
- double dimen = location.getLatitude();//維度
- longitude.setText(""+lit);
- this.dimensions.setText(""+dimen);
- float accuray=location.getAccuracy();//獲取精確度
- Log.e("", "accuray:"+accuray);
- accurText.setText(""+accuray);
- }
- else
- {
- longitude.setText("0");
- dimensions.setText("0");
- }
- }