SettingsClient.checkSettings 始终失败,状态为 LocationSettingsStatusCodes.RESOLUTION_REQUIRED

Mus*_*eed 5 android android-location kotlin google-play-services

我正在我的应用程序中使用LocationServices。在使用位置服务之前,我尝试验证具有所需设置的位置是否已打开,但我面临的问题SettingsClient.checkSettings始终是failing。请参阅我LocationRequestLocationSettingRequest建造者:

位置请求

 mLocationRequest = LocationRequest()
        mLocationRequest.interval = interval
        mLocationRequest.fastestInterval = interval

        Log.v(TAG, "distance => $distance")
        if(distance > 0) {
            mLocationRequest.smallestDisplacement = distance
        }

        mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY

        buildLocationSettingsRequest()
Run Code Online (Sandbox Code Playgroud)

位置设置RequestBuilder

private fun buildLocationSettingsRequest() {
        val builder = LocationSettingsRequest.Builder()
        builder.addLocationRequest(mLocationRequest)
        mLocationSettingsRequest = builder.build()

        mSettingsClientInit = true
    }
Run Code Online (Sandbox Code Playgroud)

checkSettings要求

mSettingsClient.checkLocationSettings(mLocationSettingsRequest)
                .addOnSuccessListener(this, object : OnSuccessListener<LocationSettingsResponse> {

                    override fun onSuccess(locationSettingsResponse: LocationSettingsResponse) {
                        Log.i(TAG, "LocationManager: All location settings are satisfied.");
                        mLocationCallback?.let {
                            fusedLocationClient?.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
                        }
//                        updateUI();
                    }
                })
                .addOnFailureListener(this, object : OnFailureListener {
                    override fun onFailure(e: Exception) {
                        Log.v(TAG, "Request PErmission failure");
                        var statusCode = (e as ApiException).getStatusCode()
                        when (statusCode) {
                            LocationSettingsStatusCodes.RESOLUTION_REQUIRED -> {
                                try {
                                    // Show the dialog by calling startResolutionForResult(), and check the
                                    // result in onActivityResult().
                                    var rae = e as ResolvableApiException;
                                    rae.startResolutionForResult(this@BaseLocationActivity, REQUEST_CHECK_SETTINGS);
                                } catch (sie: IntentSender.SendIntentException) {
                                    Log.v(TAG, "PendingIntent unable to execute request.");
                                }
                            }
                            LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> {
                                mRequestingLocationUpdates = false;
                                Log.v(TAG, "Settings change unavailable.");
                            }

                        }
                    }
                }
                )
Run Code Online (Sandbox Code Playgroud)

它始终是onFailure的结果addOnFailureListener。谁能帮我看看这可能是什么问题吗?此设置对话框显示“确定”以启用设置,我按“确定”,再次出现相同的对话框并带有 onFailure 回调。

它发生在某些设备上,而不是所有设备上。

Rah*_*ami 2

您好,按照此代码解决您的问题,我添加了 GPSUtils 类,借助该类您可以轻松管理 GPS。

\n\n

GpsUtils.类

\n\n
import android.annotation.SuppressLint;\nimport android.app.Activity;\nimport android.content.Context;\nimport android.content.IntentSender;\nimport android.location.LocationManager;\nimport android.support.annotation.NonNull;\nimport android.util.Log;\nimport android.widget.Toast;\nimport com.google.android.gms.common.api.ApiException;\nimport com.google.android.gms.common.api.ResolvableApiException;\nimport com.google.android.gms.location.LocationRequest;\nimport com.google.android.gms.location.LocationServices;\nimport com.google.android.gms.location.LocationSettingsRequest;\nimport com.google.android.gms.location.LocationSettingsResponse;\nimport com.google.android.gms.location.LocationSettingsStatusCodes;\nimport com.google.android.gms.location.SettingsClient;\nimport com.google.android.gms.tasks.OnFailureListener;\nimport com.google.android.gms.tasks.OnSuccessListener;\nimport static android.content.ContentValues.TAG;\npublic class GpsUtils {\nprivate Context context;\n    private SettingsClient mSettingsClient;\n    private LocationSettingsRequest mLocationSettingsRequest;\n    private LocationManager locationManager;\n    private LocationRequest locationRequest;\npublic GpsUtils(Context context) {\n        this.context = context;\n        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);\n        mSettingsClient = LocationServices.getSettingsClient(context);\nlocationRequest = LocationRequest.create();\n        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);\n        locationRequest.setInterval(10 * 1000);\n        locationRequest.setFastestInterval(2 * 1000);\n        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()\n                .addLocationRequest(locationRequest);\n        mLocationSettingsRequest = builder.build();\n//**************************\n        builder.setAlwaysShow(true); //this is the key ingredient\n        //**************************\n    }\n// method for turn on GPS\n    public void turnGPSOn(onGpsListener onGpsListener) {\nif (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {\n            if (onGpsListener != null) {\n                onGpsListener.gpsStatus(true);\n            }\n        } else {\n            mSettingsClient\n                    .checkLocationSettings(mLocationSettingsRequest)\n                    .addOnSuccessListener((Activity) context, new OnSuccessListener<LocationSettingsResponse>() {\n                        @SuppressLint("MissingPermission")\n                        @Override\n                        public void onSuccess(LocationSettingsResponse locationSettingsResponse) {\n//  GPS is already enable, callback GPS status through listener\n                            if (onGpsListener != null) {\n                                onGpsListener.gpsStatus(true);\n                            }\n                        }\n                    })\n                    .addOnFailureListener((Activity) context, new OnFailureListener() {\n                        @Override\n                        public void onFailure(@NonNull Exception e) {\n                            int statusCode = ((ApiException) e).getStatusCode();\n                            switch (statusCode) {\n                                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:\ntry {\n                                        // Show the dialog by calling startResolutionForResult(), and check the\n                                        // result in onActivityResult().\n                                        ResolvableApiException rae = (ResolvableApiException) e;\n                                        rae.startResolutionForResult((Activity) context, AppConstants.GPS_REQUEST);\n                                    } catch (IntentSender.SendIntentException sie) {\n                                        Log.i(TAG, "PendingIntent unable to execute request.");\n                                    }\n                                    break;\n                                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:\n                                    String errorMessage = "Location settings are inadequate, and cannot be " +\n                                            "fixed here. Fix in Settings.";\n                                    Log.e(TAG, errorMessage);\nToast.makeText((Activity) context, errorMessage, Toast.LENGTH_LONG).show();\n                            }\n                        }\n                    });\n        }\n    }\npublic interface onGpsListener {\n        void gpsStatus(boolean isGPSEnable);\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

对于 SettingsClient\xe2\x80\x99s 失败回调,将显示 GPS 对话框,并将导致 Activity\xe2\x80\x99s onActivityResult()。所以基本上如果用户同意打开 GPS,我们就可以在我们的活动中启用 GPS 标志。

\n\n
@Override\nprotected void onActivityResult(int requestCode, int resultCode, Intent data) {\n    super.onActivityResult(requestCode, resultCode, data);\n    if (resultCode == Activity.RESULT_OK) {\n        if (requestCode == AppConstants.GPS_REQUEST) {\n            isGPS = true; // flag maintain before get location\n        }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

现在在获取位置之前调用 GpsUtils 类。

\n\n
new GpsUtils(this).turnGPSOn(new GpsUtils.onGpsListener() {\n    @Override\n    public void gpsStatus(boolean isGPSEnable) {\n        // turn on GPS\n        isGPS = isGPSEnable;\n    }\n});\n
Run Code Online (Sandbox Code Playgroud)\n