我在我的应用程序中通过单击按钮以存储到数据库中获取与 FusedLocationProviderClient 的坐标。问题是,当我重新启动手机或模拟器时,它.getLastLocation()
是空的,我必须再次单击我订购的按钮才能使其工作。如果值为空,有没有办法强制获取当前位置location from .lastKnownPosition()
?
// 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()
并使用纬度、经度和准确度来存储到数据库中。
任何帮助表示赞赏!