문제

I'm trying to understand if there is any potential harm on waiting until onDestroy to unregister a listener. I'm specifically referring to unsubscribing from an eventbus (otto), but believe that the answer applies to most listener pattern implementations (SharedPreferenceListener, LocationListener, static references, etc).

I have seen several other answers to this problem that quote the phrase 'onDestroy is not guaranteed to be called'. The full onDestroy documentation text actually reads:

Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.

I understand this to mean that onDestroy should not be used for the saving of data as it may not be called before the application process is killed (as the lifecycle diagram shows us).

Simply, are there any situations where an Activity registered as a listener may be leaked due to onDestroy not being called?

도움이 되었습니까?

해결책

are there any situations where an Activity registered as a listener may be leaked due to onDestroy not being called?

Not that I can think of. However, that is not the same as:

Unregistering listeners in onDestroy - what's the harm?

The reason you unregister listeners in earlier lifecycle methods (e.g., onPause()/onStop()) is because the activity does not need those events when it is not in the foreground.

Your application already has to deal with the case where the activity is destroyed, such as by the user pressing the BACK button, but then the user later returning to the same spot in the app. You will need to create a new instance of the activity, and that activity instance will need to get whatever it needs to show from some data source. Hence, if that code works, you can use the same "get whatever it needs" logic to refresh an existing activity instance when it comes back to the foreground. IOW, treat a returning activity no different than a newly-created activity in terms of where you are getting your data.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top