android getLastKnownLocation()返回始终返回null

时间:2014-02-19 16:03:41

标签: java android geolocation google-play-services

我正在创建一个仅在用户点击按钮时检查位置的应用。

这是我的代码,当我调用getLastKnownLocation时它返回null,即使在我调用requestLocationUpdates之后:

public void main(String[] args, int iteration, Context context){
    Criteria criteria = new Criteria();
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    LocationListener loc_listener = new LocationListener() {
        public void onLocationChanged(Location l) {
        }
        public void onProviderEnabled(String p) {}
        public void onProviderDisabled(String p) {}
        public void onStatusChanged(String p, int status, Bundle extras) {}

        };

    String bestProvider = locationManager.getBestProvider(criteria, false);
    locationManager.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
    Location location = locationManager.getLastKnownLocation(bestProvider);
    location = locationManager.getLastKnownLocation(bestProvider);
    double lat;
    double lon;
    try {
        lat = location.getLatitude();
        lon = location.getLongitude();

    } catch (NullPointerException e) {
        lat = -1.0;
        lon = -1.0;

    }
    Log.i("results:",  String.valueOf(lat) + " " + String.valueOf(lon) + " 10NN");}}

启用设备上的位置服务。 非常感谢!

2 个答案:

答案 0 :(得分:1)

getLastKnownLocation将返回null,直到触发回调onLocationChanged()为止。即使天空清晰可见,GPS也可能需要几分钟。如果你在室内,它可能永远不会运行。你必须等待它运行。

答案 1 :(得分:1)

试试这个

  mGoogleMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {

                    @Override
                    public boolean onMyLocationButtonClick()
                        {

                            Location myLocation = mGoogleMap.getMyLocation();
                            onLocationChanged(myLocation);
                            return false;
                        }
                });