1

I wonder is there any ways to catch event by BroadCast receiver in Android. Because I want to do stuffs in particular time. For instance: I want to update my room database in specific time. Please help.

bovietvidai
  • 105
  • 5

1 Answers1

2

I hope this is what you need. My data handling is all in the viewmodel. So I just created an instance of Viewmodel and called it in onReceive() of the broadcast.

  // update toDO
        ToDoViewModel.instance?.apply {
             //logic here
        }

This is my code in ViewModel

 companion object {
    var instance: ToDoViewModel? = null
}
init {
    instance = this
}

Then onCleared I set instance to null to avoid memory leak.

 override fun onCleared() {
    super.onCleared()
    instance = null
}

I hope this helps you.

theroom_582002
  • 124
  • 1
  • 4