When exactly is it leak safe to use (anonymous) inner classes?

I have been reading some articles on memory leaks in Android and watched this interesting video from Google I/O on the subject.

Still, I don’t fully understand the concept, and especially when it is safe or dangerous to user inner classes inside an Activity.

This is what I understood:

A memory leak will occur if an instance of an inner class survives longer than its outer class (an Activity).
-> In which situations can this happen?

In this example, I suppose there is no risk of leak, because there is no way the anonymous class extending OnClickListener will live longer than the activity, right?

    final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.dialog_generic);
    Button okButton = (Button) dialog.findViewById(R.id.dialog_button_ok);
    TextView titleTv = (TextView) dialog.findViewById(R.id.dialog_generic_title);

    // *** Handle button click
    okButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            dialog.dismiss();
        }
    });

    titleTv.setText("dialog title");
    dialog.show();

Now, is this example dangerous, and why?

// We are still inside an Activity
_handlerToDelayDroidMove = new Handler();
_handlerToDelayDroidMove.postDelayed(_droidPlayRunnable, 10000);

private Runnable _droidPlayRunnable = new Runnable() { 
    public void run() {
        _someFieldOfTheActivity.performLongCalculation();
    }
};

I have a doubt regarding the fact that understanding this topic has to do with understanding in detail what is kept when an activity is destroyed and re-created.

Is it?

Let say I just changed the orientation of the device (which is the most common cause of leaks). When super.onCreate(savedInstanceState) will be called in my onCreate(), will this restore the values of the fields (as they were before orientation change)? Will this also restore the states of inner classes?

I realize my question is not very precise, but I’d really appreciate any explanation that could make things clearer.

3 Answers
3

Leave a Comment