[英]Android Location listener is not working
I would like to get current device location and open Google Maps
with this: 我想获取当前设备位置并使用以下方法打开
Google Maps
:
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 ? 为什么以及如何解决?
"Why..."
“为什么...”
Because requestLocationUpdates()
is an asynchorous operation and the result (the location) is returned in the onLocationChanged()
callback. 因为
requestLocationUpdates()
是异步操作,并且结果(位置)在onLocationChanged()
回调中返回。 The location isn't available immediately. 该位置无法立即使用。
"...and how to fix it ?"
“ ...以及如何解决?”
Move your Google map intent code there: 将您的Google地图意图代码移到此处:
@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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.