android Handler、Looper、Messsage、MessageQueue源码解析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangwo1991/article/details/80202582

Handler:发送和接收消息

Looper:消息(循环)轮询器

Message:消息池

MessageQueue:消息队列。虽然名为队列,但事实上它的内部存储结构并不是真正的队列,而是采用单链表的数据结构来存储消息列表的

先来看Handler,其实系统很多东西都是通过Handler消息来实现的,其中也包括activity的生命周期,应用程序的退出等;在ActivityThread类中的main方法中可以很清楚的看到,同时main方法也是android应用程序的主入口;

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

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

        // Set the reporter for event logging in libcore
        EventLogger.setReporter(new EventLoggingReporter());

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

        Process.setArgV0("<pre-initialized>");
	//实例化一个main Looper
        Looper.prepareMainLooper();
	//实例化ActivityThread
        ActivityThread thread = new ActivityThread();
	//调用attach方法
        thread.attach(false);
	//通过ActivityThread获取Handler对象
        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");
    }

在实例化一个main looper的时候调用的是prepareMainLooper();方法;prepareMainLooper();方法是Looper类中的方法;

public static void prepareMainLooper() {
	//调用prepare方法
        prepare(false);
        synchronized (Looper.class) {
	//这里需要注意只能实例化一个main Looper对象,多次实例化会报错
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

prepare();方法这里就暂时不讲了,后面会讲到,实例化完mian looper后,就会去实例化ActivityThread对象并调用其中的attach()方法及getHandler()方法去实例化一个Handler对象;

final Handler getHandler() {
	//mH extends Handler 在加载ActivityThread的时候就已经初始化了
        return mH;
    }
private class H extends Handler {
        public static final int LAUNCH_ACTIVITY         = 100;
        public static final int PAUSE_ACTIVITY          = 101;      
        public static final int DESTROY_ACTIVITY        = 109;
        public static final int EXIT_APPLICATION        = 111;
        public static final int STOP_SERVICE            = 116;

        String codeToString(int code) {
            if (DEBUG_MESSAGES) {
                switch (code) {
                    case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
                    case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
                    case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
                    case EXIT_APPLICATION: return "EXIT_APPLICATION";                   
                    case STOP_SERVICE: return "STOP_SERVICE";                  
                }
            }
            return Integer.toString(code);
        }
        public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
            switch (msg.what) {
                case LAUNCH_ACTIVITY: {
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
                    final ActivityClientRecord r = (ActivityClientRecord) msg.obj;

                    r.packageInfo = getPackageInfoNoCheck(
                            r.activityInfo.applicationInfo, r.compatInfo);
                    handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                } break;              
                case PAUSE_ACTIVITY: {
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
                    SomeArgs args = (SomeArgs) msg.obj;
                    handlePauseActivity((IBinder) args.arg1, false,
                            (args.argi1 & USER_LEAVING) != 0, args.argi2,
                            (args.argi1 & DONT_REPORT) != 0, args.argi3);
                    maybeSnapshot();
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                } break;                
                case DESTROY_ACTIVITY:
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityDestroy");
                    handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
                            msg.arg2, false);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;              
                case EXIT_APPLICATION:
                    if (mInitialApplication != null) {
                        mInitialApplication.onTerminate();
                    }
                    Looper.myLooper().quit();
                    break;                
                case STOP_SERVICE:
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStop");
                    handleStopService((IBinder)msg.obj);
                    maybeSnapshot();
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;                
            }         
    }
H类就是一个内部类,看到LAUNCH_ACTIVITY、PAUSE_ACTIVITY、EXIT_APPLICATION、STOP_SERVICE等很多消息标识,这样通过handler消息来控制activity的生命周期以及一些其他东西;当msg.what为EXIT_APPLICATION时,应用程序就会退出,并不是activity的生命周期都会走,当消息标识为EXIT_APPLICATION应用程序就已经退出了,而应用程序的退出时调用Looper中的quit方法;
public void quit() {
        mQueue.quit(false);
    }

这里就粗略而过,后面会详细讲;这是一些系统handler的使用,还是看看平时开发中的使用吧;

public class MainActivity extends AppCompatActivity {
    Handler mHanlder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //开启子线程
        new MyThread().start();
    }

    class MyThread extends Thread implements Runnable {
        @Override
        public void run() {
            super.run();
            //实例化消息轮询器
            Looper.prepare();
            //实例化handler对象
            mHanlder = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                }
            };
            //获取message对象
            Message message = mHanlder.obtainMessage();
            message.what = 1;
            //发送消息
            mHanlder.sendMessage(message);
            //开启looper轮询器
            Looper.loop();
        }
    }
}

这是一段在子线程中实例化handler的代码,当然了也可以不在线程中实例化handler,这样子就不需要实例化一个Looper,系统已经实现了的,如果在子线中实例化handler就需要同样实例化一个Looper,确保handler所在线程和Looper所在的线程一致,否则会报错;

先来看第一步Looper.prepare()实例化一个Looper;

public static void prepare() {
    prepare(true);
}

private static void prepare(boolean quitAllowed) {
    //调用prepare方法quitAllowed就为true,调用的是prepareMainLooper方法quitAllowed就是false
    //sThreadLocal.get()是直接从ThreadLocal池中获取 这里同样只能实例化一个Looper,多次实例化会报错
    if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
    }
    //直接new 一个Looper,并将实例化的Looper对象添加到ThreadLocal池中
    sThreadLocal.set(new Looper(quitAllowed));
}

在new 一个looper的时候会去实例化一个MessageQueue对象;

private Looper(boolean quitAllowed) {
    //直接实例化一个MessageQueue对象
    mQueue = new MessageQueue(quitAllowed);
    //获取当前线程
    mThread = Thread.currentThread();
}

第二步handler的实例化

handler提供多个构造方法,可以传入一个Looper,Callback回调等,这里直接用了无参构造;

public Handler() {
    this(null, false);
}
public Handler(Callback callback, boolean async) {
    if (FIND_POTENTIAL_LEAKS) {
        final Class<? extends Handler> klass = getClass();
        if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                (klass.getModifiers() & Modifier.STATIC) == 0) {
            Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                klass.getCanonicalName());
        }
    }
    //获取实例化好的looper对象,这里是从ThreadLocal池中直接获取的
    mLooper = Looper.myLooper();
    //如果获取到的looper对象为null就会报错,所以要保证实例化好的looper对象和handler对象所在的线程要一致,
    //也就是平时如果在子线程中实例化handler没有实例化looper报错的原因
    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread that has not called Looper.prepare()");
    }
    //获取MessageQueue对象,MessageQueue对象在实例化looper的构造方法中就已经实例化好了
    mQueue = mLooper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}
public static @Nullable Looper myLooper() {
//myLooper是looper类中的方法,从ThreadLocal池中直接获取looper对象
    return sThreadLocal.get();
}

第三步Message对象的实例化,通过obtainMessage();方法获取的Message对象,当然也可以直接new 一个Message,不过建议使用obtainMessage();方法获取;

public final Message obtainMessage()
{
    //调用Handler类中的obtainMessage方法,返回一个Message对象,不过调用的是Message中的obtain方法,并将Handler本身做参数传入
    return Message.obtain(this);
}
public static Message obtain(Handler h) {
//这里又调用了Message中的obtain()方法
    Message m = obtain();
//将传入的handler对象赋值给Message中的target变量
    m.target = h;
    return m;
}
/**
  * Return a new Message instance from the global pool. Allows us to
	返回一个Message实例,从全局池中
  * avoid allocating new objects in many cases.
  */
public static Message obtain() {
    synchronized (sPoolSync) {
	//判断Message池是否为null
        if (sPool != null) {
	    //不为null就将sPool对象赋值个m
            Message m = sPool;
	    //又将m中的赋值给sPool 这里是链表结构
            sPool = m.next;
            m.next = null;
            m.flags = 0; // clear in-use flag
            sPoolSize--;
	    //将获取到的message实例返回
            return m;
        }
    }
    //sPool为null的情况下直接new 一个Message对象并返回
    return new Message();
}

Message类中还提供了recycleUnchecked()方法,用于handler消息的回收,这里暂不说;Message对象有了,调用sendMessage()发送消息,当然了Handler类中不只这一个方法可以发送消息,还有其他的方法,具体可以看Handler源码;

/**
  * Pushes a message onto the end of the message queue after all pending messages
  * before the current time. It will be received in {@link #handleMessage},
  * in the thread attached to this handler.
  *  
  * @return Returns true if the message was successfully placed in to the 
  *         message queue.  Returns false on failure, usually because the
  *         looper processing the message queue is exiting.
  */
public final boolean sendMessage(Message msg)
{
    return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
    //delayMillis延迟发送的时间 毫秒值
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
    //获取MessageQueue对象,mQueue是在实例化handler时,通过looper对象获取,最初是在实例化looper对象的构造方法中实例化的
    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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    //将当前的handler赋值给Message中的handler
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

走到这里就会去调用MessageQueue中的enqueueMessage()方法;

boolean enqueueMessage(Message msg, long when) {
        //msg.target就是handler对象,上面已经进行了赋值操作
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }

        synchronized (this) {
            if (mQuitting) {
		//已经取消了
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
		//调用recycle方法,如果没有被回收就会调用recycleUnchecked()方法进行handler消息的回收
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;
	    //创建新的Message对象,并赋值
            Message p = mMessages;
            boolean needWake;
	    //创建的message对象为null或者没有延迟发送消息或者延迟发送消息的时间小于发送的时间
            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;
    }

这样子就将消息添加到队列中了,通过Looper.loop();开启轮询去取消息;

/**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */
    public static void loop() {
	//获取looper对象,如果为null说明没有实例化looper对象,会报错
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
	//获取MessageQueue对象,MessageQueue对象是在实例化looper对象的构造方法中实例化的
        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死循环,不管是ActivityThread中的void main方法,还是平时使用loop()方法都是在最后面调用,这样不会阻塞
        for (;;) {
	    //这里是链表结构,通过next()去获取每一个message对象
            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.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
		//将获取到的message消息通过handler中的dispatchMessage方法进行分发
                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);
            }
	    //通过messsage中的recycleUnchecked方法对消息进行回收
            msg.recycleUnchecked();
        }
    }
Message next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
	//消息循环
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
		//尝试检索下一条消息。如果找到,返回。
		//获取时间  从开机到现在的毫秒数(手机睡眠的时间不包括在内);
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
			//将msg赋值给prevMsg
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
			//获取到的时间消息消息的时间
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
			//下一条消息尚未准备好。设置一个超时,以便在准备就绪时唤醒。
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }

                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }

                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler

                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
    }
/**
  * Handle system messages here.
  */
public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
	//设置了callback就会走这里
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
	//这里是没有设置callback
        handleMessage(msg);
    }
}
/**
  * Subclasses must implement this to receive messages.
  *实例化handler的时候都会去重写该方法,在该方法中进行消息的处理
  */
public void handleMessage(Message msg) {
}

在消息处理完毕后,还会对消息进行回收的;

/**
     * Recycles a Message that may be in-use.
     * Used internally by the MessageQueue and Looper when disposing of queued Messages.
     */
    void recycleUnchecked() {
        // Mark the message as in use while it remains in the recycled object pool.
        // Clear out all other details.
        flags = FLAG_IN_USE;
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        replyTo = null;
        sendingUid = -1;
        when = 0;
        target = null;
        callback = null;
        data = null;

        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }

Looper.loop();中是一个死循环,所以在使用handler消息的时候需要注意当页面销毁后要将消息移除掉,避免造成内存泄漏什么的;handler提供一些移除消息的方法;

/**
  * Remove any pending posts of callbacks and sent messages whose
  * <var>obj</var> is <var>token</var>.  If <var>token</var> is null,
  * all callbacks and messages will be removed.
  */
public final void removeCallbacksAndMessages(Object token) {
    //token为null的时候所有的callback和messages都会被移除掉
    mQueue.removeCallbacksAndMessages(this, token);
}
当然也可以移除指定的消息或者callback;上面就是对handler消息的一些源码分析。


猜你喜欢

转载自blog.csdn.net/wangwo1991/article/details/80202582