下面是我的示例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()
}
}