将Android服务绑定到AndroidViewModel是一个好习惯吗?

时间:2018-12-05 06:21:04

标签: android android-architecture-components android-service-binding android-viewmodel

下面是我的示例Client和AndroidViewModel实现。假设所有绑定和取消绑定都已处理完毕,这是从AndroidViewModel与绑定服务进行通讯的好方法吗?

class ServiceViewModel(application: Application) : AndroidViewModel(application){

    private var serviceClient = ServiceClient(application)

    override fun onCleared() {
        serviceClient.close()
        println("cleared view model")
    }

    fun talkToService(){
        serviceClient.executeSomeMethod()
    }

}

class ServiceClient(private val context: Context) : ServiceConnection, AutoCloseable {

    init {
        bindService()
    }

    override fun close() {
        unbindService()
    }

    //..onServiceConnected gives IBinder
    //..onServiceDisconnected notifies


    fun executeSomeMethod(){
        binder.executeSomeServiceMethod()
    }


}

0 个答案:

没有答案