Reputation: 561
Scenario
Let Activity A implements a listener say OnCompleteListener. This listener will be passed to another thread for a network call. Thus when the webservice is completed, we get a callback to the activity A.
Question
Suppose the web service call has started and in between, the screen is rotated, thus the activity's current instance will get destroyed. Since we passed the reference of A for the web service, will it get destroyed? Will the initial instance of A get leaked?
If memory gets leaked, then how can we clean up the unwanted instance? What are the best alternatives for callbacks that land on Activities?
Upvotes: 2
Views: 1013
Reputation: 3253
It will be "destroyed" in android sense. onPause()
, onStop()
, onDestroy()
will be called but object itself will be leaked. So it is highly not recommended to do that. What you want is view listening to updates from data layer. When network call finishes it will push updates to listeners (Activity) if it exists, otherwise it will cache data. When activity comes back after rotation it can check cache for results.
Upvotes: 1
Reputation: 10152
For your first question: Yes, it will cause memory leak.
Background tasks running independently of the activity life cycle can be a hassle. If we setup a network call listener, it will hold a reference to your activity to update data. Now if the device were to be rotated, a new activity would be created replacing the old one. Since a system service will most definitely outlive any activity, your "network manager - which will trigger update event for listeners" will still hold a reference to the old activity, making it impossible for the GC to reclaim the resources still tied to that "old" activity, resulting in memory being leaked.
If you want to check, dump Java heap and use Analyzer Tasks
and look at Reference Tree
where the reference that is keeping the activity alive can be identified.
For your second question: No, you cannot clean leaked memory/unwanted instance,.. even force GC to work using System.gc()
. Simply because GC don't know if this instance is still in-use or not. If it see there is still a reference to your instance, it will mark this instance as reachable and do NOT sweep out.
If it's possible GC should already have its functionality and developers are not getting headache day by day caring about memory leaks.
Upvotes: 3