2

The Android app starts a background service that updates the Activity. If the app is closed, the service continues to collect data. When the user re-opens the app, it needs all the data from the background service which was collected while the app was closed. What is the best way to implement this?

One idea which came to mind is using an SQLite DB. However, I'm not sure how that would work. Would an event bus work?

Raw Hasan
  • 1,096
  • 1
  • 9
  • 25
SA DL
  • 73
  • 1
  • 3
    Does this answer your question? [Communication between Activity and Service](https://stackoverflow.com/questions/20594936/communication-between-activity-and-service) – Krystian G Aug 17 '21 at 13:23

1 Answers1

1

Room with LiveData will work very well in this situation. so instead of updating your Activity from Service, insert data in the Room database. Then use a LiveData Observer in your Activity, which will be notified whenever Room dataset changes. this allows you to remove the coupling between your Activity and Service and write code in reactive fashion. this will look something as

In Service

val data = dataCapturedByService
roomDatabase.yourDao().insertData(data)

In Activity

// Return type of fetchData is LiveData<YourModel>
roomDatabase.yourDao().fetchData().observe(this, Observer{
   // This will be called every time Room dataset changes
   // Update UI or something else
}

Checkout Room documentation and tutorials

mightyWOZ
  • 7,946
  • 3
  • 29
  • 46