Android 定位當前位置可能出現的問題

android關於LocationManager的gps定位android

LocationManager提供了兩種定位當前位置的方法 GPS和NETWORK 其中gps的偏差大概50m左右 network大概500mgit

起初當gps打開後 我使用Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);來獲取location 但是一直爲null不知道是什麼緣由 網上搜了好久終於找到了解決方案ide


android有一個Criteria類能夠直接判斷當前適合用gps或者network 而且設置LocationListener監聽器實時更新location 直接上代碼ui


private void getLocalAddress() {this

 LocationManager locationManager;spa

        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);orm

        

        Criteria criteria = new Criteria();rem

        criteria.setAccuracy(Criteria.ACCURACY_FINE);get

        criteria.setAltitudeRequired(false);it

        criteria.setBearingRequired(false);

        criteria.setCostAllowed(true);

        criteria.setPowerRequirement(Criteria.POWER_LOW);

        String provider = locationManager.getBestProvider(criteria, true);

        

        Location location = locationManager.getLastKnownLocation(provider);

        //updateWithNewLocation(location);

        locationManager.requestLocationUpdates(provider, 2000, 10,

                        locationListener);

        updateWithNewLocation(location);

}



private final LocationListener locationListener = new LocationListener() {

public void onLocationChanged(Location location) {

updateWithNewLocation(location);

}


public void onProviderDisabled(String provider) {

updateWithNewLocation(null);

}


public void onProviderEnabled(String provider) {

}


public void onStatusChanged(String provider, int status, Bundle extras) {

}

};



private void updateWithNewLocation(Location location) {

String latLongString;

TextView myLocationText;

if (location != null) {

double lat = location.getLatitude();

double lng = location.getLongitude();

latLongString = "緯度:" + lat + "\n經度:" + lng;

} else {

latLongString = "沒法獲取地理信息";

}

Toast.makeText(SearchXiaoQuActivity.this, latLongString,

Toast.LENGTH_LONG).show();

}

相關文章
相關標籤/搜索