I'm working on an Android project, in which I need to load some images to a GridView. The images could be in the cache, if cache missing, then query the Internet server. My design is to use two threads to do the loading task. One thread for reading cache and one thread for downloading. So there are 3 threads including the UI one. Each of them has its own message queue and uses Handler to communicate.
My question is whether I should use bound service in this situation instead? Actually I have realized the design above and it seems nothing wrong but GC is working very hard, which can be inferred from the logcat.
Another issue is that several threads exist when I use DDMS to monitor the threads. This is because the same loading mechanism is used in several Activities. I have let the threads quit its message loop while onPause() is called, I'm sure only two of them are alive in the same time. But I can see all of them in DDMS. (BTW, why the threads still exist? I have let thread = null;)
So in a word, my question is: Could this loading task benefit from a bound service?
Started services run until they are stopped or destroyed and do not inherently provide a mechanism for interaction or data exchange with other components. Bound services, on the other hand, provide a communication interface to other client components and generally run until the last client unbinds from the service.
A bound service is the server in a client-server interface. It allows components (such as activities) to bind to the service, send requests, receive responses, and perform interprocess communication (IPC).
A service is termed as bounded when an application component binds itself with a service by calling bindService() method. To stop the execution of this service, all the components must unbind themselves from the service by using unbindService() method.
After the client receives the IBinder, it can begin interacting with the service through that interface. onBind(): The system invokes this method by calling bindService() when another component wants to bind with the service (such as to perform RPC).
So why are you using multiple threads? You need to load an image in the background, and when done, display it in the UI. It really doesn't matter to the UI where the images comes from. And using multiple threads doesn't make it faster, just consumes more memory. Just use a single background thread: first it hits the cache, then downloads if no hit.
Services are for when you want do something that doesn't need a UI. If you need to update the UI in real time, a service doesn't make much sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With