Android SettingsClient.checkSettings始终失败,需要状态位置SettingsStatusCodes.RESOLUTION\u

Android SettingsClient.checkSettings始终失败,需要状态位置SettingsStatusCodes.RESOLUTION\u,android,kotlin,google-play-services,android-location,Android,Kotlin,Google Play Services,Android Location,我正在应用程序中使用LocationServices。在使用location services之前,我试图验证是否启用了具有所需设置的location,但我面临的问题是设置客户端。检查设置始终失败。请参见我的LocationRequest和LocationSettingRequestbuilder: 定位请求 mLocationRequest = LocationRequest() mLocationRequest.interval = interval mLo

我正在应用程序中使用
LocationServices
。在使用location services之前,我试图验证是否启用了具有所需设置的location,但我面临的问题是
设置客户端。检查设置
始终
失败
。请参见我的
LocationRequest
LocationSettingRequest
builder:

定位请求

 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()
LocationSettingRequestBuilder

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

        mSettingsClientInit = true
    }
我请求
checkSettings
as

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.");
                            }

                        }
                    }
                }
                )
mSettingsClient.checkLocationSettings(mlLocationSettingsRequest)
.addOnSuccessListener(此,对象:OnSuccessListener{
成功覆盖乐趣(位置设置响应:位置设置响应){
Log.i(标记“LocationManager:满足所有位置设置”);
mLocationCallback?让我来{
fusedLocationClient?.RequestLocationUpdate(mlLocationRequest、mlLocationCallback、Looper.myLooper());
}
//updateUI();
}
})
.addOnFailureListener(此,对象:OnFailureListener{
覆盖失败(e:异常){
Log.v(标记“请求权限失败”);
var statusCode=(e作为ApiException).getStatusCode()
何时(状态代码){
位置设置StatusCodes.RESOLUTION_必需->{
试一试{
//通过调用startResolutionForResult()显示对话框,并检查
//导致onActivityResult()。
var rae=e作为可解决的异常;
rae.StartResult解决方案(this@BaseLocationActivity,请求检查设置);
}捕获(sie:IntentSender.SendIntentException){
Log.v(标记“PendingEvent无法执行请求”);
}
}
位置设置StatusCodes.SETTINGS\u CHANGE\u不可用->{
mRequestingLocationUpdates=false;
Log.v(标记“设置更改不可用”);
}
}
}
}
)
它总是导致
addOnFailureListener
onFailure
。有人能帮我吗?有什么问题吗?此设置对话框显示“确定”要启用设置,请按“确定”,再次显示同一对话框和onFailure回调

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


您好,按照这段代码来解决您的问题,我添加了GPSUtils类,借助这个类您可以轻松管理GPS

GpsUtils.Class

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

new GpsUtils(this).turnGPSOn(new GpsUtils.onGpsListener() {
    @Override
    public void gpsStatus(boolean isGPSEnable) {
        // turn on GPS
        isGPS = isGPSEnable;
    }
});

您是否尝试使用不同于
priority\u HIGH\u accurity
()的优先级?否,即使设备处于高精度模式,也会启用网络和GPS,仍然会返回此checkLocationSettingsfailure@MustansarSaeed refered dis``问题是,即使在某些设备中,侦听器成功的所有条件都得到满足,但仍然会发生错误,而且并非总是如此,,
new GpsUtils(this).turnGPSOn(new GpsUtils.onGpsListener() {
    @Override
    public void gpsStatus(boolean isGPSEnable) {
        // turn on GPS
        isGPS = isGPSEnable;
    }
});