Android Activity Garbage Collection

2019-06-06 04:14发布

问题:

I noticed this behavior while developing a simple Android game which has 2 activities.

The game has 2 activities, the first is a screen which allows the user to select the opponent type, level etc. and the second the actual game screen. The second activity creates an object of a GameManager class which handles all the game processing. This GameManager class also creates a CountDownTimer which it starts to prompt user input (on timeout the game is defaulted to the opponent).

I've noticed that if the user exits the second activity (returns to the first) and then launches a new game again, the previous timer is still running until completion. I've handled this by explicitly cancelling the timer (from the onDestroy() of the second activity) as just setting the timerobject to 'null' did not cancel the timer.

However I'm curious as to why the previous timer was running even after my activity was exited the first time? Shouldn't the GC have deleted all the objects instantiated by the second Activity (and whatever child objects it created) when it was exited? Would be great to know the reason behind the observed behavior?

TIA

回答1:

Shouldn't the GC have deleted all the objects instantiated by the second Activity (and whatever child objects it created) when it was exited?

This isn't how Garbage Collection works. The GC isn't responsible for 'deleting objects' - it's responsible for picking up 'orphaned' objects and freeing their resources. Even then, a GC isn't guaranteed to get to all of the orphans in a timely manner.

Further to that, any objects which may be 'system' objects and need to be released explicitly may never be released if your code doesn't do it. Other issues with GC may include creating objects which other threads (other than the Activity which created them) may have a reference to.

You mention your 'timer' but don't explain what sort of class you are using for it. I suggest read up specifically about that class and see what the implications are for ceation/deletion (possibly explicit 'release' of resources).

GC is a very grey area on any platform. With Android it's normally pretty immediate but with the nature of the Activity life-cycle it's very difficult to predict what will happen.

In general make use of onCreate, onPause and onResume within Activities and also things like savedInstanceState and SharedPreferences to keep track of what is going on.



回答2:

CountDownTimer is not bound to an activity as you already found out. A hint to lookout for in these cases is that a class does not receive any Context in its constructor. Hence it can't be bound to an activity.