我从2015年的Google I/O大会上了解到,Google Play服务中有一个新的对话框,用户不需要退出当前应用程序就可以打开位置。下面的图片显示了它的外观:
现在我的问题是,如何在我的项目中实现这个功能?我已经搜索过了,但没有找到有效的答案,请帮忙!
我从2015年的Google I/O大会上了解到,Google Play服务中有一个新的对话框,用户不需要退出当前应用程序就可以打开位置。下面的图片显示了它的外观:
现在我的问题是,如何在我的项目中实现这个功能?我已经搜索过了,但没有找到有效的答案,请帮忙!
使用 Kotlin
通过进行以下更改,此解决方案适用于 Activity
和 Fragment
:
对于 Activity resolvableApiException.startResolutionForResult(this@MainActivity, REQUEST_CHECK_SETTING)
对于 Fragment
startIntentSenderForResult(resolvableApiException.resolution.intentSender, REQUEST_CHECK_SETTING, null, 0, 0,0,null)
通过使用 LocationSettingsResponse 可以实现此任务。
在 MainActivity.kt 中。
private fun checkLocationSetting()
{
locationRequest = LocationRequest.create()
locationRequest.apply {
priority=LocationRequest.PRIORITY_HIGH_ACCURACY
interval = 5000
fastestInterval = 2000
}
val builder = LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest)
builder.setAlwaysShow(true)
val result: Task<LocationSettingsResponse> = LocationServices.getSettingsClient(applicationContext)
.checkLocationSettings(builder.build())
result.addOnCompleteListener {
try{
val response: LocationSettingsResponse = it.getResult(ApiException::class.java)
Toast.makeText(this@MainActivity, "GPS is On", Toast.LENGTH_SHORT).show()
Log.d(TAG, "checkSetting: GPS On")
}catch(e:ApiException){
when(e.statusCode){
LocationSettingsStatusCodes.RESOLUTION_REQUIRED ->{
val resolvableApiException = e as ResolvableApiException
// for fragment change below line to: startIntentSenderForResult(resolvableApiException.resolution.intentSender, REQUEST_CHECK_SETTING, null, 0, 0,0,null)
resolvableApiException.startResolutionForResult(this@MainActivity, REQUEST_CHECK_SETTING)
Log.d(TAG, "checkSetting: RESOLUTION_REQUIRED")
}
LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> {
// USER DEVICE DOES NOT HAVE LOCATION OPTION
}
}
}
}
}
onActivityResult
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when(requestCode)
{
REQUEST_CHECK_SETTING ->{
when(resultCode){
Activity.RESULT_OK->{
Toast.makeText(this@MainActivity, "GPS is Turned on", Toast.LENGTH_SHORT).show()
}
Activity.RESULT_CANCELED ->{
Toast.makeText(this@MainActivity, "GPS is Required to use this app", Toast.LENGTH_SHORT).show()
}
}
}
}
}
完整代码链接 MainActivity.kt
输出:
完整代码链接 MainActivity.kt
SettingsApi
:https://developer.android.com/reference/com/google/android/gms/location/SettingsApi.html - CommonsWare