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 我最近发现,如果设备启用了省电模式或设备位置精度设置为低,那么该请求将失败,并显示相同的状态代码。
答案 0 :(得分:2)
在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"/>