task.getResult() 返回 null?

3

在设置中开启位置信息后,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());
    }

嗨@Arthurghev,你找到为什么currentLocation总是null的原因了吗?我也遇到了同样的问题。 - hetmanJIIIS
你找到解决方案了吗?我也遇到了同样的问题。 - devu mani
2个回答

1
有点晚了,但我希望这可以成为以后参考的资料。
主要问题在于如果用户关闭了手机位置,则所有最后位置都会被手机系统清除,因此onComplete监听器的task.getResult()将为null。在这种情况下,应使用onSuccess监听器,如果位置为null,则使用getCurrentLocation()获取用户的最后位置。保留HTML标签。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接