开发者

Data exchange between a service and an activity

开发者 https://www.devze.com 2023-04-10 10:54 出处:网络
I have to publish the progress from a background service on the UI continuously on a progress bar. Any ideas on how to go about it. Intents won\'t work I guess coz they can only send the data once the

I have to publish the progress from a background service on the UI continuously on a progress bar. Any ideas on how to go about it. Intents won't work I guess coz they can only send the data once the activity is started. Ant other suggestions?

Up开发者_C百科date : The progress on the UI happens on a progress Bar


Extend Application, which is created once for entire application.

When Activity starts, store its reference to a field in your Application object. (Note that you can access Application using Activity.getApplication). Set this field to Activity reference or null in onPause/onResume calls.

Then in Service, you have also access to your Application by Service.getApplication. So look if your Activity reference is non-null, meaning that your Activity is shown to user, and update UI as needed in such case, by calling methods on your Activity.


Thanks for the help mice, but since I needed to update progress bars on different activities in my app depending on which one was visible, I found it easier to implement through Broadcast Intents and Recievers and Intent Filters. All I had to do was to Broadcast the progress in my service wrapped up in a bundle via a broadcast Intent (with a custom Intent Filter applied) and register (in onResume()) an inner subclass of BroadcastReciever in the activities which needed the progress (having the same intent filter). One can also unregister these recievers in the onPause() method of the activity to save memory headspace.

0

精彩评论

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

关注公众号