Please clarify is code listed below would lead to context memory leak? Thanks
public class HelperClass {
private Context context;
public HelperClass(Context context) {
this.context = context;
}
public void myHelperMethod() {
// uses this.context
}
}
public class MyActivity extends Activity {
private HelperClass helper;
public void onCreate(Bundle savedInstanceState) {
helper = new HelperClass(this);
}
}
The short answer is no. What you want to beware of is a reference to the context/activity that remains after the activity has been destroyed. A device rotation is an example of an action that would cause the current activity to be destroyed by Android.
In this case, your activity is the only thing that holds a reference to your helper class. Thus when the activity is destroyed, there will be no more existing references.
If however your activity class defined the reference to the helper as a static, then that would cause a memory leak. The static reference would remain even after the activity instance was destroyed. The helper class, which holds a reference to the activity, would then prevent the activity instance from being garbaged collected.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments