3

I know that if you initialize a Handler directly and use it in an Activity it will leak Context (courtesy of Alex Lockwood), for e.g.

public class SampleActivity extends Activity {

  private final Handler mLeakyHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      /* ... */
    }
  }
}

So I used the following approach

private static class StaticHandler extends Handler {

    private final WeakReference<SampleActivity> mSampleAct;

    private StaticHandler(SampleActivity act) {
        mSampleAct = new WeakReference<SampleActivity>(
                act);
    }

}

Then I initialize it as following

 public class SampleActivity extends Activity {
    private Handler myHandler = new StaticHandler(this) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            processTask(msg.obj);
        }
    };
}

I wanted to know if my Handler i.e. myHandler will still leak Context, how can I be sure it doesn't?

Arif Nadeem
  • 8,524
  • 7
  • 47
  • 78

1 Answers1

2

Using a WeakReference is definitely a smart way to avoid memory leaks. The code looks good to me out of context, but the best way to ensure that it will not leak memory is to use the DDMS memory analyzer. Read more: Memory Analyzer Tool in android?

Community
  • 1
  • 1
Phil
  • 35,852
  • 23
  • 123
  • 164