Android Location listener is not working

放肆的年华 提交于 2019-12-24 11:04:33

问题


I would like to get current device location and open Google Maps with this:

  if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        LocationListener locationListener = new MyLocationListener();
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);


    } else {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_LOCATION_REQUEST_CODE);
    }




private class MyLocationListener implements LocationListener {

    @Override
    public void onLocationChanged(Location loc) {

        longitude = loc.getLongitude();
        latitude = loc.getLatitude();

        Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr=" + latitude + "," + longitude + "&daddr=55.877526, 26.533898"));
        startActivity(intent);
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

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

But this code is not working: for some reasons listener is ignored.

Why and how to fix it ?


回答1:


"Why..."

Because requestLocationUpdates() is an asynchorous operation and the result (the location) is returned in the onLocationChanged() callback. The location isn't available immediately.

"...and how to fix it ?"

Move your Google map intent code there:

@Override
public void onLocationChanged(Location loc) {

    longitude = loc.getLongitude();
    latitude = loc.getLatitude();

    Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr=" + latitude + "," + longitude + "&daddr=55.877526, 26.533898"));
    startActivity(intent);

}


来源:https://stackoverflow.com/questions/40576882/android-location-listener-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!