memory_leaks_in_android _ identify_treat_and_avoid
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revision | |||
| memory_leaks_in_android _ identify_treat_and_avoid [2016/10/11 17:14] – [Inner classes] kalaschnikow | memory_leaks_in_android _ identify_treat_and_avoid [2018/04/23 15:57] (current) – external edit 127.0.0.1 | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| + | ====== Memory leaks in Android — identify, | ||
| + | by Johan Olsson | ||
| + | Original: https:// | ||
| + | |||
| + | |||
| + | ===== Registering listeners ===== | ||
| + | |||
| + | Don't forget to unregister | ||
| + | |||
| + | To find a leak use " | ||
| + | |||
| + | |||
| + | ===== Inner classes ===== | ||
| + | Inner classes creates implicit reference to the enclosing class. Especially inner classes implementing AsyncTask can have this problem, because Activity have different life cycle as inner class. Activity can be destroyed, but the reference to it will be hold, because of inner AsyncTask class. | ||
| + | Possible solution: The inner class should be made static. | ||
| + | |||
| + | |||
| + | If the inner class needs some data from enclosing task, it should be delivered to it through constructor. If this data contains Context (if we for example need a textView from an activity, this textview will contain Context), then we can use WeakReference for it. Example: | ||
| + | < | ||
| + | private static class BackgroundTask extends AsyncTask< | ||
| + | |||
| + | private final WeakReference< | ||
| + | |||
| + | public BackgroundTask(TextView resultTextView) { | ||
| + | | ||
| + | this.textViewReference = new WeakReference<> | ||
| + | |||
| + | } | ||
| + | ... | ||
| + | </ | ||
| + | |||
| + | ===== Anonymous classes ===== | ||
| + | Anonymous classes have the same problem as inner classes: they hold instance to the enclosing class. We can use here the same solution. | ||
| + | |||
| + | ===== Conclusion ===== | ||
| + | |||
| + | * Favor static inner classes over non-static. | ||
| + | Each non-static inner class will have an implicit reference to its outer class instance which may result in unwanted behaviors. Instead define these classes as static and store life cycle references needed as WeakReferences. | ||
| + | * Consider other means of background service. | ||
| + | Android offers a wide variety of ways to get work off the main thread such as HandlerThread, | ||
| + | * Do not blindly rely on the garbage collector. | ||
| + | When coding in a garbage collected language it’s easy to make the assumption, that memory management does not have to be taken into consideration. Our examples clearly show that this is not the case. Therefore, make sure that your allocated resources are all collected as expected. | ||
| + | |||
| + | |||
