1 /* 2 * Copyright (C) 2015 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License 15 */ 16 17 package com.android.tv.common; 18 19 import android.os.Handler; 20 import android.os.Looper; 21 import android.os.Message; 22 import android.support.annotation.NonNull; 23 import java.lang.ref.WeakReference; 24 25 /** 26 * A Handler that keeps a {@link WeakReference} to an object. 27 * 28 * <p>Use this to prevent leaking an Activity or other Context while messages are still pending. 29 * When you extend this class you <strong>MUST NOT</strong> use a non static inner class, or the 30 * containing object will still be leaked. 31 * 32 * <p>See <a href="http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html"> 33 * Avoiding memory leaks</a>. 34 */ 35 public abstract class WeakHandler<T> extends Handler { 36 private final WeakReference<T> mRef; 37 38 /** 39 * Constructs a new handler with a weak reference to the given referent using the provided 40 * Looper instead of the default one. 41 * 42 * @param looper The looper, must not be null. 43 * @param ref the referent to track 44 */ 45 public WeakHandler(@NonNull Looper looper, T ref) { 46 super(looper); 47 mRef = new WeakReference<>(ref); 48 } 49 50 /** 51 * Constructs a new handler with a weak reference to the given referent. 52 * 53 * @param ref the referent to track 54 */ 55 public WeakHandler(T ref) { 56 mRef = new WeakReference<>(ref); 57 } 58 59 /** Calls {@link #handleMessage(Message, Object)} if the WeakReference is not cleared. */ 60 @Override 61 public final void handleMessage(Message msg) { 62 T referent = mRef.get(); 63 if (referent == null) { 64 return; 65 } 66 handleMessage(msg, referent); 67 } 68 69 /** 70 * Subclasses must implement this to receive messages. 71 * 72 * <p>If the WeakReference is cleared this method will no longer be called. 73 * 74 * @param msg the message to handle 75 * @param referent the referent. Guaranteed to be non null. 76 */ 77 protected abstract void handleMessage(Message msg, @NonNull T referent); 78 } 79