Handlerメモリの漏洩を避ける

3131 ワード

handlerはactivityに対して参照を持ち、activityがページを終了するとhandlerが非静的な内部クラスであるため外部クラスに対して持つ、簡単な方法はonDestroyでremove
@Override
protected void onDestroy() {
    super.onDestroy();
    mHandler.removeCallbacksAndMessages(null);
}

同時にhandlerをstaticに設定することでactivityの保有によるメモリ漏洩を回避
private MyHandler handler;
// handler  
static class MyHandler extends Handler {
    private WeakReference weakReference;

    public MyHandler(MainActivityactivity) {
        this.weakReference = new WeakReference(activity);
    }

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        MainActivityTwo activity = weakReference .get();
        if(activity !=null){

 			switch (msg.what) {
          		  case 1:
					activity .  ui
             	   break;
        }
        }
     
    }
}
	 handler = new MyHandler(this);
    Message message = Message.obtain();
    message.what = 1;
    handler.handleMessage(message);


Message  Message.obtain();
 Message 
/**
* Run the message queue in this thread. Be sure to call
	* {@link #quit()} to end the loop.
*/

public static void loop() {
final Looper me = myLooper();
if (me == null) {
    throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;

// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();

for (;;) {
    Message msg = queue.next(); // might block
    if (msg == null) {
        // No message indicates that the message queue is quitting.
        return;
    }

    // This must be in a local variable, in case a UI event sets the logger
    final Printer logging = me.mLogging;
    if (logging != null) {
        logging.println(">>>>> Dispatching to " + msg.target + " " +
                msg.callback + ": " + msg.what);
    }

    final long traceTag = me.mTraceTag;
    if (traceTag != 0) {
        Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
    }
    try {
        msg.target.dispatchMessage(msg);
    } finally {
        if (traceTag != 0) {
            Trace.traceEnd(traceTag);
        }
    }

    if (logging != null) {
        logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
    }

    // Make sure that during the course of dispatching the
    // identity of the thread wasn't corrupted.
    final long newIdent = Binder.clearCallingIdentity();
    if (ident != newIdent) {
        Log.wtf(TAG, "Thread identity changed from 0x"
                + Long.toHexString(ident) + " to 0x"
                + Long.toHexString(newIdent) + " while dispatching to "
                + msg.target.getClass().getName() + " "
                + msg.callback + " what=" + msg.what);
    }

    msg.recycleUnchecked();
}
}
 :  
msg.target.dispatchMessage(msg);