gpt4 book ai didi

android - .getLastLocation() FusedLocationProviderClient 的位置数据为空

转载 作者:行者123 更新时间:2023-11-29 15:34:33 24 4
gpt4 key购买 nike

我通过单击按钮在我的应用程序中获取与 FusedLocationProviderClient 的坐标以存储到数据库中。问题是,当我重新启动手机或模拟器时,.getLastLocation() 为 null,我必须再次单击我订购的按钮才能使其正常工作。如果 location from .lastKnownPosition() 的值为 null,是否有办法强制获取当前位置?

// Google fused location client for GPS position
private FusedLocationProviderClient flpc;
// Vars to store GPS info
public Double latitude, longitude;
public Float accuracy;


// Google Fused Client for location
public void getLocation() {
// FusedLocationProviderClient
flpc = LocationServices.getFusedLocationProviderClient(context);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
......
return;
}

// Get the latest position from device
Task<Location> task = flpc.getLastLocation();

task.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if(location!=null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
accuracy = location.getAccuracy();
}
}
});
}

在我的按钮处理程序中,我调用 getLocation() 并使用纬度、经度和精度存储到数据库中。

感谢任何帮助!

最佳答案

当getLastLocation()为null时,需要发起LocationRequest

private LocationRequest locationRequest;
private LocationCallback locationCallback;

...

locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(20 * 1000);
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
txtLocation.setText(String.format(Locale.US, "%s -- %s", wayLatitude, wayLongitude));
}
}
}
};
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper())

如果您不需要持续更新,您可以在收到请求后将其删除。

mFusedLocationClient.removeLocationUpdates(locationCallback);

更多信息在这里:https://medium.com/@droidbyme/get-current-location-using-fusedlocationproviderclient-in-android-cb7ebf5ab88e

关于android - .getLastLocation() FusedLocationProviderClient 的位置数据为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53896970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com