Handler原理

一、Handler的基本用法

1.1 在主线程发送消息,在主线程中处理消息

在主线程中使用Handler,注意这里handler需要加static将其变为内部类,从而不持有MainActivity对象,避免了Activity退出时,而Handler持有MainActivity导致的内存泄露。

public class MainActivity extends AppCompatActivity {
    private static final int MSG =1;
    private static final String TAG = "Handler";
    private static Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = getApplicationContext();
        handler.sendEmptyMessage(MSG);
    }

    private static Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if(msg.what == MSG){
                Toast.makeText(mContext,"接收到消息",Toast.LENGTH_SHORT);
            }
            return false;
        }
    });
}

1.2 在子线程中发送消息,在主线中处理消息

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "Handler";
    private static Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = getApplicationContext();
    }

    private static Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if(msg.what == 100){
                String word = (String)msg.obj;
                Log.d("kkjj","word--->"+word);
            }
            return false;
        }
    });


    public void send(View view) {
        if(view.getId() == R.id.btn){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Message msg = Message.obtain();
                    msg.what = 100;
                    msg.obj = "子线程发送消息";
                    handler.sendMessage(msg);
                }
            }).start();
        }
    }
}

结果:
Handler原理

二、Handler源码

2.1、Message是如何添加到MessageQueue

当使用sendMessage发送消息时,调用sendMessageDelayed调用延时发送消息,并且默认延时时间设置为0

public final boolean sendMessage(@NonNull Message msg) {
        return sendMessageDelayed(msg, 0);
    }

修正延时时间,若开发者使用sendMessageDelayed发送消息设置的延时小于0,则系统默认会将时间修改为0。

public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

获取消息队列,将消息队列、消息、消息延时时间传入enqueueMessage。MessageQueue什么时候创建的,待会再看。

public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis) {
    MessageQueue queue = mQueue;
    if (queue == null) {
        RuntimeException e = new RuntimeException(
                this + " sendMessageAtTime() called with no mQueue");
        Log.w("Looper", e.getMessage(), e);
        return false;
    }
    return enqueueMessage(queue, msg, uptimeMillis);
}

继续调用MessageQueue的enqueueMessage

private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
            long uptimeMillis) {
        msg.target = this;
        msg.workSourceUid = ThreadLocalWorkSource.getUid();

        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

这里采用以延时时间为关键key的优先级队列,通过循环将发送的Message插入到优先级队列中。看到Message中含有next和prev,就可以看出此优先级队列就是个双向链表。

boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }

        synchronized (this) {
            if (msg.isInUse()) {
                throw new IllegalStateException(msg + " This message is already in use.");
            }

            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue.  Usually we don't have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

2.2 MessageQueue、Looper是如何创建的呢?

回想App启动流程ActivityThread的main方法中创建了主线程的Looper,主线程的Looper系统在启动App时已经帮忙开发者创建好了。若需要在子线程中使用Handler,则开发者需要自己调用Looper.prepare创建子线程的looper。

public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");

        // Install selective syscall interception
        AndroidOs.install();

        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        // Call per-process mainline module initialization.
        initializeMainlineModules();

        Process.setArgV0("<pre-initialized>");

        Looper.prepareMainLooper();

        // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
        // It will be in the format "seq=114"
        long startSeq = 0;
        if (args != null) {
            for (int i = args.length - 1; i >= 0; --i) {
                if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                    startSeq = Long.parseLong(
                            args[i].substring(PROC_START_SEQ_IDENT.length()));
                }
            }
        }
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

调prepare

public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

主线程调用了熟悉的Looper.prepare

public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

将Looper对象放在了ThreadLocal中,ThreadLocal类似于HashMap,其将线程id作为key,set的内容作为value,从而保证了Looper和线程的映射关系。

private static void prepare(boolean quitAllowed) {
    if (sThreadLocal.get() != null) {
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    sThreadLocal.set(new Looper(quitAllowed));
}

在此处创建了MessageQueue。
这里记住一点:Looper持有MessageQueue对象

private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

2.3 消息分发

在2.1中看到了Handler发送的消息被添加到了MessageQueue中,那么添加的消息是如何被分发出去的呢。

在Looper.loop中,在主线程中通过死循环不断从MessageQueue中获取消息,从这里可以看出Massage持有Handler对象。

public static void loop() {
        final Looper me = myLooper();
        me.mInLoop = true;
        final MessageQueue queue = me.mQueue;
        boolean slowDeliveryDetected = false;

        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);
            }
            // Make sure the observer won't change while processing a transaction.
            final Observer observer = sObserver;

            final long traceTag = me.mTraceTag;
            long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
            long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
            if (thresholdOverride > 0) {
                slowDispatchThresholdMs = thresholdOverride;
                slowDeliveryThresholdMs = thresholdOverride;
            }
            final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
            final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

            final boolean needStartTime = logSlowDelivery || logSlowDispatch;
            final boolean needEndTime = logSlowDispatch;

            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }

            final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
            final long dispatchEnd;
            Object token = null;
            if (observer != null) {
                token = observer.messageDispatchStarting();
            }
            long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid);
            try {
            //根据Massage将消息发送到指定Handler处理回调Handler的handlerMessage
                msg.target.dispatchMessage(msg);
                if (observer != null) {
                    observer.messageDispatched(token, msg);
                }
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } catch (Exception exception) {
                if (observer != null) {
                    observer.dispatchingThrewException(token, msg, exception);
                }
                throw exception;
            } finally {
                ThreadLocalWorkSource.restore(origWorkSource);
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (logSlowDelivery) {
                if (slowDeliveryDetected) {
                    if ((dispatchStart - msg.when) <= 10) {
                        Slog.w(TAG, "Drained");
                        slowDeliveryDetected = false;
                    }
                } else {
                    if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                            msg)) {
                        // Once we write a slow delivery log, suppress until the queue drains.
                        slowDeliveryDetected = true;
                    }
                }
            }
            if (logSlowDispatch) {
                showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
            }

            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();
        }
    }

Looper.loop在主线程中执行死循环为什么不会阻塞主线程呢?
google给了一句注释:可能会阻塞

Message msg = queue.next(); // might block

这里调用到了linux的epoll机制和pipe机制,这里总结就是:在没有消息时阻塞线程并进入休眠释放cpu资源,有消息时唤醒线程

Message next() {
  nativePollOnce(ptr, nextPollTimeoutMillis);
}

三、问题

3.1 Handler使用不当为什么会造成内存泄漏

如上面流程可知:

a、Looper在prepare时创建了MessageQueue对象,Looper持有MessageQueue对象
b、Message消息被存放在MessageQueue的优先级队列中
c、Message在Looper.loop方法中根据Massage将消息发送到指定Handler处理回调Handler的handlerMessage

因此形成引用链:

Looper--->MessageQueue--->Message--->Handler--->Activity

当Acitivity退出时,由于引用链的存在,根据可达性分析,Activity并不能被垃圾回收器回收,因此造成内存泄漏。
解决方法思路
打断引用了链路任意位置:
如在Handler处加static是变为静态内部类,不持有外部类引用

3.2 handler为什么可以跨线程通信

从上面的分析可以,当子线程创建Handler实例对象之前,必须调用Looper.prepare创建MessageQueue和Looper对象,将Looper对象存放在ThreadLocal,每个线程对应一个MessageQueue和looper,并且子线程会调用Looper.loop循环读取消息。

当主线程调用handler发送一个message的时候,将message插入到handler对应的MessageQueue中,此时子线程通过观察者观察到新消息的添加,因此触发msg.target.dispatchMessage(msg)将消息发送给子线程的Handler

private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

将当前Thread和Looper保存在ThreadLocalMap中

public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
上一篇:Handler机制


下一篇:Android之Handler