我想在关闭GPS时看到设置对话框(要求)以关闭GPS,因为我的应用程序需要GPS。我已经为此编写了代码,并将其放在MainActivity中的onCreate()
中,但对话框仅在应用程序运行时显示,但我想在应用程序中关闭GPS时看到此对话框。
val settingsClient = LocationServices.getSettingsClient(this)
val locationRequest = LocationRequest()
val builder =
LocationSettingsRequest.Builder().addLocationRequest(locationRequest)
.setAlwaysShow(false)
.setNeedBle(false)
settingsClient.checkLocationSettings(builder.build())
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val response = task.result ?: return@addOnCompleteListener
val locationSettingsStates =
response.locationSettingsStates
Log.e("yyy", locationSettingsStates.toString())
// TODO
}
}
.addOnFailureListener { e ->
Timber.i("checkLocationSetting onFailure:" + e.message)
when ((e as ApiException).statusCode) {
LocationSettingsStatusCodes.RESOLUTION_REQUIRED -> {
Timber.i("Location settings are not satisfied. Attempting to upgrade " + "location settings ")
try {
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
val rae = e as ResolvableApiException
rae.startResolutionForResult(this, 0)
} catch (sie: IntentSender.SendIntentException) {
Timber.i("PendingIntent unable to execute request.")
}
}
else -> {
}
}
}
}
2条答案
按热度按时间brccelvz1#
这是一种方法:
我创建了一个LocationUtil类:
然后创建一个包含以下函数的文件:
最后,我使用了MainActivity中的代码:
fumotvh32#
让数据层
LocationRepository
具有如下gpsStatus
流如何然后在UI层观察,以隐藏/显示对话框。