Reputation: 24573
I have a case in my Android application in which I need to perform a long running task. At the end of that task I will use that info. I have multiple activities that need to access that info and I do not need to recalculate it each time.
The simple answer is create a 'static' class that can store the info. If the info is not yet there, it can start an AsyncTask to get the info. If the info has already been obtained/calculated it can just give back the info.
However I am wondering if a service is a better pattern/idea in this case. Can I use a service in Android, have that service obtain the data and allow other activities to ask that service for the data?
Upvotes: 0
Views: 164
Reputation: 1
If the information is needed at different points of the Application life cycle then, then I would suggest storing it using shared preference. That would give you the option of accessing the information next time you would start the App.
However, if you would need to notify an activity of the availability of the information I would use some bus in the application. Incase you wanted to use Otto be mindful that it has been discontinued in faver of Rx. a link to Otto's github page
Upvotes: 0
Reputation: 1006614
However I am wondering if a service is a better pattern/idea in this case
If the task will take longer than a second or so, I recommend the use of IntentService
. That way, if your app moves to the background while the work is going on (e.g., incoming phone call), Android is less likely to terminate your process, allowing you to complete your work.
If the task will take longer than 10-15 seconds, I recommend the use of a WakeLock
as well, perhaps in the form of my WakefulIntentService
. Otherwise, the device may fall asleep while the work is being done.
and allow other activities to ask that service for the data?
You only want a service around while it is actively delivering value to the user. Sitting around waiting for activities to ask it questions is not actively delivering value to the user. IntentService
automatically destroys itself when the work is complete.
When the data is ready, use an in-process event bus (e.g., greenrobot's EventBus, Square's Otto, LocalBroadcastManager
) to tell interested parties that the data is ready. If you also need to hold onto the results past that point, use an appropriate feature of the bus (e.g., sticky events with greenrobot's EventBus, the @Producer
pattern with Otto), or have a separate singleton cache.
Upvotes: 1