I created a service which syncs data from the web on a background thread and want to notify a list activity when the service has completed so it can update it's cursor? What would be the best way to do this? I'm thinking of sending a broadcast when the service is done but not sure if that's the best way to do it. I need to requery the cursor when the service has finished so I'm not sure if that will work well with broadcast receivers? I haven't done alot of android in awhile so thanks in advance.
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
相关文章
- android开发 怎么把图片放入drawable的文件夹下
- android上如何获取/storage/emulated/下的文件列表
- androidStudio有个箭头不认识
- SQLite不能创建表
- Windows - Android SDK manager not listing any plat
- Animate Recycler View grid when number of columns
- Why is the app closing suddenly without showing an
- Android OverlayItem.setMarker(): Change the marker
Use a
Handler
in your service that registers a client when yourListActivity
connects to the service; that is, in youronServiceConnected
method in yourListActivity
, send aMessage
to your service that enables you to keep track of connected clients. Then you can simply loop through these clients in yourService
and send them aMessage
when something takes place in yourService
that you want to notify yourListActivity
about. For more information you can look at code in an on-going project of mine: myListActivity
and myService
stub.In short, in your
MainActivity
, start and bind to your service with:Define a messenger to respond to messages from the service like:
And then write your service connection code like:
Note that the
replyTo
is the messenger we just created.In your
NetworkService
, keep track of connected clients with:and create your handler like:
Then, when you want to send a message back to your
MainActivity
, just do something like the following:If you're already using the support library, you could just as easily fire a broadcast from the service using the LocalBroadcastManager back to your activity that would listen for the broadcast being sent.
Using LocalBroadcastManager ensures only your own application would ever receive the broadcast so you don't have to worry about leaking private data or opening up potential security holes.
Also see: how to use LocalBroadcastManager?
EDIT (09/2014):
A better way to do this would be to use an event bus framework like Otto (my favourite) or GreenRobot/EventBus to avoid coupling your components too tightly.
As per The Busy Coder's Guide to Advanced Android Development