Andrew Matiuk
Andrew Matiuk

Reputation: 922

Service to Activity sticky communication

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.

Any ideas?

Upvotes: 3

Views: 400

Answers (4)

huy.nguyen
huy.nguyen

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

Karan Nagpal
Karan Nagpal

Reputation: 541

You should use massenger to send download progress, because it is more secure and less expensive method then broadcast receiver.

Upvotes: 0

Tapa Save
Tapa Save

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

Mikel
Mikel

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

Related Questions