简体   繁体   中英

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.

  • 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?

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 .

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.

Use static variables inside your Application class (extends Application). Inside Service you set this variables. Inside Activity you read periodically this variables.

您应该使用massenger发送下载进度,因为它是更安全和更便宜的方法然后广播接收器。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM