除非执行 mSettingsClient.checkLocationSettings,否则无法获取 locationSettings 的 getStatusCode

Unable to get getStatusCode of locationSettings unless mSettingsClient.checkLocationSettings is executed

有没有办法知道 LocationSettingsStatusCodes 是否等于 RESOLUTION_REQUIRED 而不必一直调用 mSettingsClient.checkLocationSettings?可能来自 onLocationChanged 侦听器的位置对象?

 mSettingsClient.checkLocationSettings(mLocationSettingsRequest).addOnSuccessListener(mActivity,
                new OnSuccessListener<LocationSettingsResponse>() {
                    @Override
                    public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                        Log.i(this.getClass().getName(), "Location settings ok");
                        mFusedProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper()).addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {
                                
                            }
                        });
                    }
                }).addOnFailureListener(mActivity, new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        int statusCode = ((ApiException) e).getStatusCode();
                        if(statusCode == LocationSettingsStatusCodes.RESOLUTION_REQUIRED){
                            //Location settings not satisfied.
                                try {
                                    // Cast to a resolvable exception.
                                    ResolvableApiException resolvable = (ResolvableApiException) e;
                                    resolvable.startResolutionForResult(
                                            mActivity,
                                            AppCommand.REQUEST_GOOGLE_ACCURACY);
                                } catch (IntentSender.SendIntentException ex) {
                                    Log.e(this.getClass().getName(), "SendIntentException " + e.getLocalizedMessage());
                                }
                            }
        
    
                        Log.e(this.getClass().getName(), "Check location permission failed: " +e.getLocalizedMessage());
                    }
                }
            );

if LocationSettingsStatusCodes is equal to RESOLUTION_REQUIRED

这不是真的。 LocationSettingsStatusCodes 等于 RESOLUTION_REQUIREDLocationSettingsStatusCodes是对失败异常处理机制的封装,但实际过程中可能会出现其他异常,我们无法保证还有哪些情况会导致权限检查失败。

当您尝试获取位置时,您不必一直检查位置设置。 mSettingsClient.checkLocationSettingsmFusedProviderClient.requestLocationUpdates这两个调用可以分开调用。由于它们是异步回调,请确保先调用 checkLocationSettings,完成后调用 requestLocationUpdate。

一个建议是在片段的 onCreate()onResume() 或 activity 中调用 checkLocationSettings。并在需要时调用 requestLocationUpdates()