Reputation: 81
I'm currently working on an app that is composed of a background IntentService running all the time (even when activity lost focus) and a Activity (a section pager with fragments).
The background service is checking time very often and storing a large array of objects (up to 300) parsed from an xml file.
Each object represent an event with an associated startTime and when this startTime matches the current time the service has to notify the activity (if available) to display that the event is happening.
On the activity side I have fragments (tabs of the section pager) with a custom arrayAdapter to list the events into a ListView.
Right now what I'm doing is sending my object from my service with a LocalBroadcastManager. Fragments are the listening and when they receive the object they simply update their local Arraylist by replacing it and notifying the ArrayAdapter that the data set changed.
Since each fragment has to keep an arrayList to update the ArrayAdapter and then the ListView, I end up with the same object stored both inside the service's array and in one of the fragment' array. I'm wondering if there is a better way.
The question : What would be the most efficient (on memory/cpu usage and speed) way to share a large array of objects between my service and my activity ?
Upvotes: 3
Views: 888
Reputation: 3958
You could use greenrobot's EventBus. I don't think you can avoid duplicating the data. If you will use the same object instance in the Service and in the Fragments, you'll have to take care to notify the adapters each and every time, otherwise you'll get errors.
You would be better off storing the downloaded objects in a local SQLite database and only loading the minimum amount of information needed in the Fragments. This would minimize the time it takes to transfer the data from the IntentService thread to the Activity's main thread (because you wouldn't even transfer the data, just send a signal to the current Fragment that the data has been updated). A ContentObservable may also help you.
Also, you shouldn't use an IntentService for tasks that run all the time. The IntentService is intended to run a single task and finish, being started again the next time you need it to run another task. You should use a plain Service with a Thread or HandlerThread inside it. You will have better control this way, and you will also be able to run multiple tasks in parallel if you need to.
Upvotes: 1