如何检查在ViewModel中授予的权限? [英] How to check permission is granted in ViewModel?
问题描述
我需要询问联系人的权限,当应用程序启动时,我要问,在ViewModel部分,我需要调用需要权限的方法.我需要检查权限是否由用户授予,然后再调用,但是要检查权限,我需要具有访问活动.而在我的ViewModel中,我没有对Activity的引用,也不想拥有我该如何克服这个问题?
I need to ask permission for contacts and when application starts I'm asking,in ViewModel part I need to call method which requires permission. I need to check permission is granted by user or not and then call, but for checking permission I need to have access Activity. while in my ViewModel I don't have a reference to Activity and don't want to have, How I can overcome, the problem?
推荐答案
我只是遇到了这个问题,所以我决定改用LiveData
.
I just ran into this problem, and I decided to use make use of LiveData
instead.
核心概念:
-
ViewModel上有一个LiveData,它需要进行哪些权限请求
ViewModel has a LiveData on what permission request needs to be made
ViewModel有一个方法(本质上是回调),该方法返回是否授予权限
ViewModel has a method (essentially callback) that returns if permission is granted or not
SomeViewModel.kt
:
class SomeViewModel : ViewModel() {
val permissionRequest = MutableLiveData<String>()
fun onPermissionResult(permission: String, granted: Boolean) {
TODO("whatever you need to do")
}
}
FragmentOrActivity.kt
class FragmentOrActivity : FragmentOrActivity() {
private viewModel: SomeViewModel by lazy {
ViewModelProviders.of(this).get(SomeViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
......
viewModel.permissionRequest.observe(this, Observer { permission ->
TODO("ask for permission, and then call viewModel.onPermissionResult aftwewards")
})
......
}
}
这篇关于如何检查在ViewModel中授予的权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!