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();

}

相关文章
相关标签/搜索