Issue
I have a Worker Service, and a bunch of Activities. Every Activity has a Handler. The Activites can start jobs by sending Intents to the Service with the startService method. These jobs get into a queue, and are processed sequentially.
To report back the results of the finished jobs, I supply the proper Activity's Handler wrapped in a Messenger object with the Intent that describes the job. The Service sends back some message for the calling Activity through this. This works just fine.
But the supplied Handlers seems to remain in memory, even after the corresponding Activites got destroyed, continuing to handle the completion messages.
- How can this be? Shouldn't the handlers be destroyed with the
Activitythey're part of? - Does this cause a memory leak?
Solution
Since the Service has a reference to the Itnents which still have a reference to the Activities Handler then the Handler isn't going to become available for Garbage Collection.
Have you seen this video from Google IO? It's about building apps that use RESTful web services so isn't directly relevant but the approach of delegating the responsibility for responding to long running events will partially map to your problem.
If you don't want to change things around too much then you need a way in your Activities onClose or onDestroy to notify the Service (and through it the Intent) that the long running task it is in charge of isn't needed anymore. It removes it's reference to the Handler and so the GC can get rid of it.
That or centralise the management (as in the video) of running tasks and responding to their lifecycle in a ServiceHelper class. That class can publish events as things happen and the activities can listen for those events.
This has the benefit of your code being in one place so you don't have to change every activity when you want to change how you handle the service.
Answered By - Paul D'Ambra
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.