task.getResult()返回null吗?

时间:2019-06-10 12:38:40

标签: android location

在设置中打开位置后,task.getResult()返回null。如果再试一次,一切都会好的。问题是什么 ? 这是代码

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());
    }

1 个答案:

答案 0 :(得分:0)

对不起,但我忘记了如何解决。我找到了这段代码,希望对您有帮助

   try {
        if (mLocationPermissionsGranted) {
            mFusedLocationProviderClient.getLastLocation()
                    .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                        @Override
                        public void onSuccess(Location location) {
                            // Got last known location. In some rare situations this can be null.
                            if (location != null) {
                                currentLocation = location;
                                isLocationEnabled = true;
                                moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()), "My Location");
                            }
                        }
                    });
        }
    } catch (SecurityException e) {
        Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage());
    }