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

时间:2018-12-22 15:32:18

标签: android android-studio location fusedlocationproviderclient

单击按钮以存储到数据库中时,我正在与我的应用程序中的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(),并使用纬度,经度和准确性存储到数据库中。

任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:1)

当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.removeLocationUpdates(locationCallback);

此处有更多信息:https://medium.com/@droidbyme/get-current-location-using-fusedlocationproviderclient-in-android-cb7ebf5ab88e

答案 1 :(得分:0)

手机重新启动后,缓存的最后一个位置将丢失,因此,如果您未打开使用GPS的应用程序(例如google地图或其他内容),那么将没有最后一个位置。

永远不必返回任何位置,您应该始终假定它可以为空。

如果要获取位置,则只需要按@tenprint在此线程中所说的那样使用LocationCallback。

请参阅此链接

Android get location is null after phone reboot