Reputation: 2251
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 ?
Upvotes: 1
Views: 2443
Reputation: 3235
"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);
}
Upvotes: 2