androidalarmmanagerbroadcastandroid-timer

Catch Alarm Manager event In Android


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.


Solution

  • 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.