如何获取用户的最后已知位置?

时间:2019-12-07 07:21:41

标签: android google-maps location

  

我正在使用FusedLocationProviderClient获取最近的已知位置。   我得到task.getResult为空。   有什么解决方案。   谢谢。

    mFusedLocationProviderClient = 
LocationServices.getFusedLocationProviderClient(MainActivity.this);
try {
    if (mLocationPermissionsGranted) {
        Task<Location> location = mFusedLocationProviderClient.getLastLocation();
        location.addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "onComplete: found location!");
                    currentLocation = task.getResult(); // task.getResult() returns null
                    if (currentLocation != null) {
                        moveCamera(new LatLng(currentLocation.getLatitude(), 
currentLocation.getLongitude()), DEFAULT_ZOOM, "My Location", cameraMovingMode);
                    }
                } else {
                    Log.d(TAG, "onComplete: current location is null");
                    Toast.makeText(MainActivity.this, "unable to get current location", 
Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
} catch (SecurityException e) {
    Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage());
}

0 个答案:

没有答案