Android 即使GPS打开,也会显示“位置设置”对话框
以上代码用于请求用户打开位置。但最近我发现,有时它会要求打开位置,即使位置已打开 编辑:1Android 即使GPS打开,也会显示“位置设置”对话框,android,location,Android,Location,以上代码用于请求用户打开位置。但最近我发现,有时它会要求打开位置,即使位置已打开 编辑:1 我最近发现,如果设备已打开电池节电模式或设备位置精度设置较低,则此请求将以相同的状态代码失败。在OnFailureListener中,您可以另外检查GPS是否打开,然后显示用户对话框。大概是这样的: val request = LocationRequest() request.interval = 1000 * 60 request.fastestInterval = 1000 * 30
我最近发现,如果设备已打开电池节电模式或设备位置精度设置较低,则此请求将以相同的状态代码失败。在
OnFailureListener
中,您可以另外检查GPS是否打开,然后显示用户对话框。大概是这样的:
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.
}
}
}
请记住,您需要在清单文件中添加以下权限
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.
}
}
}
如果启用了GPS,我在其他部分应该怎么做?@LalitJadav您可以向toast显示“GPS没有响应,请确保您没有处于电池节省模式”如果用户单击“不感谢”收到相同的响应,我想强制GPS启动。@LalitJadav在这种情况下,您可以关闭应用程序,也许用户此时不想使用GPS还有另一个原因。您只能提示用户,如果GPS没有响应,此应用将无法正常工作。请检查编辑,它只在某些情况下发生,即使用户希望启用并单击“确定”
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>