如何在android中显示位置设置对话框?
Posted
技术标签:
【中文标题】如何在android中显示位置设置对话框?【英文标题】:how to show location setting dialog in android? 【发布时间】:2015-08-17 14:31:29 【问题描述】:从 google i/o 2015 我了解到,google play 服务中有一个新对话框,用户无需退出当前应用程序即可打开位置。下图显示了它的外观:
现在我的问题是,如何在我的项目中实现它?我已经搜索了,但没有找到任何有效的答案,请帮忙!
【问题讨论】:
在 Play Services SDK 中使用SettingsApi
:developer.android.com/reference/com/google/android/gms/location/…
***.com/questions/28759454/…
【参考方案1】:
看看google service documetation 的api 你会发现一切都有据可查。 对于您的要求,我建议使用LocationSettingsRequest.Builder 来实现您的目标。
我在 *** 中找到了 Kai 的一个示例:Link
【讨论】:
有人专门找SettingsApi页面的,请参考link【参考方案2】:使用 Kotlin
通过进行以下更改,此解决方案适用于 Activity
和 Fragment
:
关于活动 resolvableApiException.startResolutionForResult(this@MainActivity, REQUEST_CHECK_SETTING)
片段
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
【讨论】:
以上是关于如何在android中显示位置设置对话框?的主要内容,如果未能解决你的问题,请参考以下文章