Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 // Copyright 2016 The Chromium Authors. All rights reserved. | |
| 2 // Use of this source code is governed by a BSD-style license that can be | |
| 3 // found in the LICENSE file. | |
| 4 | |
| 5 package org.chromium.chrome.browser; | |
| 6 | |
| 7 import android.os.Handler; | |
| 8 import android.os.Message; | |
| 9 | |
| 10 import java.lang.ref.WeakReference; | |
| 11 | |
| 12 /** | |
| 13 * Abstract Handler subclass that can be used to prevent memory leaks. Handlers may cause leaks if | |
| 14 * handling a message is delayed. Messages added to the message queue have a ref erence to the | |
| 15 * Handler and the Handler has a reference to the outer class which prevents the outer class from | |
| 16 * being garbage collected. Child classes should be static so that their lifetim e isn't tied to the | |
| 17 * containing class. | |
| 18 * <p> | |
| 19 * A sample implementation of a {@link TidyHandler} is shown below: | |
| 20 * | |
| 21 * <pre> | |
| 22 * <code> | |
| 23 * {@code public static class ExampleTidyHandler extends TidyHandler<ContainingC lass>} { | |
| 24 * public ExampleTidyHandler(ContainingClass instance) { | |
| 25 * super(instance); | |
| 26 * } | |
| 27 * | |
| 28 * {@literal @}Override | |
| 29 * public void handleMessageTidy(Message m, ContainingClass instance) { | |
| 30 * instance.doSomeInstanceMethodThatHandlesTheMessage(); | |
| 31 * } | |
| 32 * } | |
| 33 * </code> | |
| 34 * </pre> | |
| 35 * | |
| 36 * @param <T> The containing class. | |
| 37 */ | |
| 38 public abstract class TidyHandler<T> extends Handler { | |
| 39 | |
| 40 private WeakReference<T> mClassReference; | |
|
Ted C
2016/09/13 17:25:54
For the places that use this, do we actually have
| |
| 41 | |
| 42 public TidyHandler(T instance) { | |
| 43 mClassReference = new WeakReference<T>(instance); | |
| 44 } | |
| 45 | |
| 46 @Override | |
| 47 public void handleMessage(Message m) { | |
| 48 T instance = mClassReference.get(); | |
| 49 if (instance != null) { | |
| 50 handleMessage(m, instance); | |
| 51 } | |
| 52 } | |
| 53 | |
| 54 protected void baseHandlerHandleMessage(Message m) { | |
| 55 super.handleMessage(m); | |
| 56 } | |
| 57 | |
| 58 protected abstract void handleMessage(Message m, T instance); | |
| 59 } | |
| OLD | NEW |