LocationSettings 对话框出现,即使 GPS 打开

LocationSettings Dialog Appears even if GPS turn on

val request = LocationRequest()
    request.interval = 1000 * 60
    request.fastestInterval = 1000 * 30
    request.smallestDisplacement = 10f
    request.priority = LocationRequest.PRIORITY_HIGH_ACCURACY

    val builder = LocationSettingsRequest.Builder().addLocationRequest(request)
    builder.setAlwaysShow(true)
    val result = LocationServices.getSettingsClient(this).checkLocationSettings(builder.build())
    result.addOnFailureListener {
        if (it is ResolvableApiException) {
            // Location settings are not satisfied, but this can be fixed
            // by showing the user a dialog.
            try {
                // Show the dialog by calling startResolutionForResult(),
                // and check the result in onActivityResult().
                it.startResolutionForResult(this, 1)
            } catch (sendEx: IntentSender.SendIntentException) {
                // Ignore the error.
            }

        }

    }

以上代码用于要求用户打开位置。不过最近发现有的时候即使开启了定位也要求开启定位

编辑:1 我最近发现,如果设备开启了节电模式或设备位置精度设置为低,则此请求将失败并显示相同的状态代码。

OnFailureListener 中您还可以检查 GPS 是打开还是关闭,然后显示用户对话框。像这样:

result.addOnFailureListener {
    if (it is ResolvableApiException) {
        try {
           val lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
           val gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);

           if(!gps_enabled) {
               it.startResolutionForResult(this, 1)
           } else {
               powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
               val locationMode = Settings.Secure.getInt(activityUnderTest.getContentResolver(), Settings.Secure.LOCATION_MODE)

            // location mode status:
            //  0 = LOCATION_MODE_OFF
            //  1 = LOCATION_MODE_SENSORS_ONLY
            //  2 = LOCATION_MODE_BATTERY_SAVING
            //  3 = LOCATION_MODE_HIGH_ACCURACY

               if(powerManager.powerSaverMode) {
                   //show dialog to turn off the battery saver mode
               } else if (locationMode != 3){
                  //show dialog that "make sure your location accuracy is not low"
               }
           }
        } catch (sendEx: Exception) {
            // Ignore the error.
        }

    }

}

请记住,您需要在清单文件中添加以下权限。

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>