Timmmm..
11
这是我制作的一个有用的小课程,你可以使用.可悲的是,它仍然非常冗长,因为你不能拥有匿名的静态内部类.
import java.lang.ref.WeakReference;
import android.os.Handler;
import android.os.Message;
/** A handler which keeps a weak reference to a fragment. According to
* Android's lint, references to Handlers can be kept around for a long
* time - longer than Fragments for example. So we should use handlers
* that don't have strong references to the things they are handling for.
*
* You can use this class to more or less forget about that requirement.
* Unfortunately you can have anonymous static inner classes, so it is a
* little more verbose.
*
* Example use:
*
* private static class MsgHandler extends WeakReferenceHandler
* {
* public MsgHandler(MyFragment fragment) { super(fragment); }
*
* @Override
* public void handleMessage(MyFragment fragment, Message msg)
* {
* fragment.doStuff(msg.arg1);
* }
* }
*
* // ...
* MsgHandler handler = new MsgHandler(this);
*/
public abstract class WeakReferenceHandler extends Handler
{
private WeakReference mReference;
public WeakReferenceHandler(T reference)
{
mReference = new WeakReference(reference);
}
@Override
public void handleMessage(Message msg)
{
if (mReference.get() == null)
return;
handleMessage(mReference.get(), msg);
}
protected abstract void handleMessage(T reference, Message msg);
}
if(mReference.get()== null)返回; handleMessage(mReference.get(),msg); 这是一个糟糕的方法,因为在null检查和handleMessage之间,引用仍然可能是gc'ed导致空指针异常,因此它是一种更好的方法来将返回值存储在T reference = mReference.get(); 然后检查null并将局部变量传递给handleMessage方法. (4认同)