I need to download elements from internet and add them to an arraylist in the background. (The download may take a few minutes.)
There is a loop in which part of overall elements are downloaded each iteration and added to the list. I need different activities be able to have access to that arraylist whenever needed, no matter if the download (the loop) is in progress or finished.
It seems a service can do this, but i don't have any idea on how. Considering the code below, how can i achieve this?
class A extends Service {
void foo(){
//uses a loop to get elements from internet
//then adds the elements to myArraylist in each loop
}
}
class B extends Activity {
//needs to have access to myArraylist asynchronously
}
class C extends Activity {
//needs to have access to myArraylist asynchronously
}
Note that i need the download process stay active when user switches between activities.
Using the structure recommended by Nick Cardoso but with many changes to meet my case, i managed to solve the problem. here it is:
And here is my Application class:
Here is the activity which needs to access the shared arraylist
Do not forget to register MyApplication and MyService in manifest.
So the problem you face with what you are asking is that your download loop may be adding to or changing the list while the active activity may also be accessing the same list. This can cause a
ConcurrentModificationException
. To avoid this what you need to do is synchronise all activity with the list. In order to make it available to all activities and have it accessible to your service I would suggest that the list itself is stored in your application (a class extendingApplication
)You would write to it as follows
And Read
Please just treat this as pseudo code, I've written it on the train home so the method signatures may vary, but this should get you where you need to be
You can do it by Broadcast receiver.For send the data on other activity you can use:
For receive this message for other any activity you can use this code: