[英]How to get phone device location using FusedLocationProviderClient
I am using the FusedLocationProviderClient to get the devices location when the proximity sensor is acitvated. 我正在使用FusedLocationProviderClient来获取接近传感器被激活时的设备位置。 When the user gets close to the proximity sensor the program should get the devices location however it isnt getting to the nessasary code because I think it gets stuck at the .isSucessful() if statement. 当用户靠近接近传感器时,程序应该获取设备位置,但是它没有得到nessasary代码,因为我认为它被卡在.isSucessful()if语句中。
private FusedLocationProviderClient mFusedLocationProviderClient;
private void getDeviceLocation() {
mFusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(this);
try {
if ( ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
return;
}
} catch (Exception e) {
e.printStackTrace();
}
final Task location = mFusedLocationProviderClient.getLastLocation();
Log.d("Works to here:","here");
location.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if ( task.isSuccessful() ) {
Location currentLocation = (Location) task.getResult();
double lat = currentLocation.getLatitude();
double lon = currentLocation.getLongitude();
Log.d("workes to here:",String.valueOf(lat));
addMarker(lat, lon);
final LatLng sydney = new LatLng(lat, lon);
mapFragment.mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
googleMap.addMarker(new MarkerOptions().position(sydney));
}
});
}
}
});
}
Don't use getLastLocation. 不要使用getLastLocation。 It will almost always return null, because it doesn't find the location, it only returns one if the location was already cached. 它几乎总是返回null,因为它找不到位置,如果位置已经缓存,它只返回一个。 Instead, use requestLocationUpdates to get the location on a callback when its available. 相反,使用requestLocationUpdates在回调可用时获取回调的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.