Reputation: 922
I have a service that downloads some data from internet and periodically sends progress to the indicator activity. In the end of processing service sends a result.
I have a question what is the best way to achieve persistence of the communication.
Messenger or ResultReceiver, I need to parcel them into Intent and store list of listeners in the service. But on configuration change activity destroys, and it's hard to maintain this list.
LocalBroadcastManager, I need to migrate from Messages to Intents, and also there is no sticky send in this class. So if I get result while my progress activity is in background result will be lost.
BroadcastManager is good, but I don't need to broadcast my progress system wide, and security issues.
Any ideas?
Upvotes: 3
Views: 400
Reputation: 454
You may want to give Otto (http://square.github.io/otto/) a try.
In your service, whenever you want to communicate with the activity, post a new event using a shared Bus
. You should do that on main thread with a handler or main looper since you are probably using IntentService
. The service may act as a producer as well. When your activity is recreated, current known value will be posted.
Your activity just needs to register with the Bus
and subscribes to the right event. When it is paused, just unregister with the Bus
.
Upvotes: 2
Reputation: 541
You should use massenger to send download progress, because it is more secure and less expensive method then broadcast receiver.
Upvotes: 0
Reputation: 4857
Use static variables inside your Application class (extends Application). Inside Service you set this variables. Inside Activity you read periodically this variables.
Upvotes: 0
Reputation: 1621
I belive the best way to achieve that persistance is:
After the service downloads, you should save your data in a database or a file.
The service then sends broadcast to update.
If the activity is "alive" all goes well and it goes to the database/file to get the updated content.
If the activity was killed or something, you just have to make sure the data is in the database/file so that when you start/restart the activity you can get the latest content from database/file.
While downloading keep a state and progress saved in the db/file the same way.
Check this Google I/O Session, it explains this really good.
Upvotes: 0