开发者

Updating an activity's data from a service

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,开发者_StackOverflow社区 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!


When service gets new data:

  1. Saves data to your custom Application class: How to declare global variables in Android?

  2. Sends a broadcast that (possibly multiple) interested Activities listen to. Activities that are not active do not receive broadcasts.

  3. When Activity is activated, it checks if there is new data in Application (since it did not get update broadcasts when inactive).


I'd rathter use BroadcastReceiver instead of custom interface. But the technique is the same: register it in onResume(), unregister in onPause(). Service fires Intents, obviously.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜