How to check permission is granted in ViewModel?

前端 未结 3 1636
天涯浪人
天涯浪人 2021-02-08 19:53

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 gr

3条回答
  •  我寻月下人不归
    2021-02-08 20:26

    I did something like this:

    create an abstract class that extends AndroidViewModel which gives you access to the application context:

    abstract class BaseViewModel(application: Application) : AndroidViewModel(application), CoroutineScope {
    
        private val job = Job()
    
        override val coroutineContext: CoroutineContext
            get() = job + Dispatchers.Main
    
        override fun onCleared() {
            super.onCleared()
            job.cancel()
        }
    }
    

    Now, create your view model by extending the BaseViewModel class and you will have access to the application context

    class AdminViewModel(application: Application) : BaseViewModel(application) {
        .....
    }
    

    Now you always have access to a Context that you can use to get access to resources.

提交回复
热议问题