When It's Safe to Use Anonymous Inner Classes in Android
Inner Class Memory Leaks
In Android, a memory leak occurs when an inner class outlives its outer class. This can happen when the inner class holds a strong reference to the outer class, either directly or indirectly through another object.
Safe Situations to Use Anonymous Inner Classes
Using anonymous inner classes inside an Activity is generally safe when:
Example of a Safe Anonymous Inner Class
The code sample you provided in your question is an example of a safe anonymous inner class:
// This is safe because the anonymous class is a short-lived callback okButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { dialog.dismiss(); } });
Dangerous Situation to Use Anonymous Inner Classes
Using anonymous inner classes inside an Activity can be dangerous when:
Example of a Dangerous Anonymous Inner Class
The following code sample illustrates a dangerous anonymous inner class:
// This is dangerous because _droidPlayRunnable holds a long-lived reference to _someFieldOfTheActivity _handlerToDelayDroidMove = new Handler(); _handlerToDelayDroidMove.postDelayed(_droidPlayRunnable, 10000); private Runnable _droidPlayRunnable = new Runnable() { public void run() { _someFieldOfTheActivity.performLongCalculation(); } };
Understanding Activity Lifecycle and Inner Classes
Android Activities have a lifecycle that determines when they are created, resumed, paused, and destroyed. When an Activity is destroyed, its internal state is lost. This includes references to any inner classes within the Activity.
Protecting Against Memory Leaks
To avoid memory leaks in anonymous inner classes, it's important to:
The above is the detailed content of When is it Safe to Use Anonymous Inner Classes in Android?. For more information, please follow other related articles on the PHP Chinese website!