I have a service running, and one of its tasks is to regularly fetch data from an external web host. Upon finding new data, the service should update the main activity to show the most recent text. There is no need for the activity to be in the foreground during an update, but when the activity is resumed, it should reflect the most recent data from the service.
My current implementation is a bit odd, and I cannot help but think there should be a better way to do it. My approach is the following:
The activity (MainActivity) implements a custom interface OnDataChangedListener. In the MainActivity's onCreate, it calls a static method of the service to register itself (MyService.addDataChangedListener(this)).
When the service finds a data changed, it iterates over its list of listeners and calls onDataChanged(newData). Finally, the MainActivity's onDataChanged method will change the activity's text to reflect the new data.
In onPaused, I plan to unregister the listener, and re-register it in onResume. onResume will also call MyService.getDataset() to get the most recent data upon resuming the application.
This approach seems like it would not live well within the lifecycle of Android applications. Does anybody know of a better way to handle this? Thanks!