Android消息处理机制

Android消息处理机制

ActivityThread #main方法

public static void main(String[] args) {
        ...
        Looper.prepareMainLooper();
			  ...
        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();//进入Looper的loop循环

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

Looper.prepareMainLooper();

Looper.prepareMainLooper();//准备主线程的Looper

//Looper.prepareMainLooper,主要prepare(false)后给sMainLooper从ThreadLocal获取内容赋值

private static Looper sMainLooper;//static的

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

//给ThreadLocal添加内容
private static void prepare(boolean quitAllowed) {
  //如果ThreadLocal有内容的话就抛出异常,因为一个线程只能有一个Looper
  if (sThreadLocal.get() != null) {
    throw new RuntimeException("Only one Looper may be created per thread");
  }
  //给ThreadLocal插入内容
  sThreadLocal.set(new Looper(quitAllowed));
}

//从ThreadLocal获取当前线程存的Looper
public static @Nullable Looper myLooper() {
  return sThreadLocal.get();
}

//获取主线程的Looper
public static Looper getMainLooper() {
  synchronized (Looper.class) {
    return sMainLooper;
  }
}

通过上面可以看到Looper.prepareMainLooper是首先new一个Looper并将其放入到主线程的ThreadLocal中,并将其通过ThreadLocal的get方法获取后赋值给sMainLooper。

接下来看看Looper的 构造方法,在new一个Looper的时候主要都干了些什么事情。

//Looper构造方法
private Looper(boolean quitAllowed) {
  mQueue = new MessageQueue(quitAllowed);
  mThread = Thread.currentThread();
}

在new一个Looper时创建一个MessageQueue给当前的线程。并让Looper持有该消息队列的引用。

通过上述内容可以知道如果我们要获取主线程的Looper和消息队列我们可以这么做:

在主线程:
Looper mainLooper = Looper.myLooper();
或者:(也可在其他线程用)
Looper mainLooper = Looper.getMainLooper();
MessageQueue queue = mainLooper.getQueue();

接下来继续回到ActivityThread的main方法中,Looper.prepareMainLooper();执行完后接下来是 ActivityThread thread = new ActivityThread();

ActivityThread thread = new ActivityThread();

ActivityThread不是线程并没有继承Thread,只是简单普通类

ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);

构造方法:

//构造方法
ActivityThread() {
  mResourcesManager = ResourcesManager.getInstance();
}

ActivityThread的构造方法只是初始化了资源管理器。

thread.attach(false, startSeq);创建一个Binder线程。(ApplicaitonThread)

接下来继续看ActivityThread的main方法,下一步时Looper.loop();

Looper.loop();

public static void loop() {
  //从ThreadLocal获取当前线程存储的Looper,即当前的Looper
  final Looper me = myLooper();
  if (me == null) {
    throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
  }
  if (me.mInLoop) {
    Slog.w(TAG, "Loop again would have the queued messages be executed before this one completed.");
  }

  me.mInLoop = true;
  //获取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();

  // Allow overriding a threshold with a system prop. e.g.
  // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
  final int thresholdOverride =
    SystemProperties.getInt("log.looper."
                            + Process.myUid() + "."
                            + Thread.currentThread().getName()
                            + ".slow", 0);

  boolean slowDeliveryDetected = false;
  
  //开始死循环
  for (;;) {
    //获取消息队列中的下一条消息,可能会阻塞当前线程
    Message msg = queue.next(); // might block
    if (msg == null) {
      //没有消息的话退出循环,那么应用程序也就会退出。
      return;
    }
    ...
      //Message的target为Handler对象,哪一个Handler把这个Message发送到MessageQueue(消息队列),那么这个Message的target会持有这个Handler的引用。
      //回调Handler的dispatchMessage即handleMessage
    msg.target.dispatchMessage(msg);
    ...
    ...
    msg.recycleUnchecked();//将message回收到消息池中,下次要用的时候不需要重新创建,只需要Message.obtain()就可以。
  }
}

主线程(UI线程)一直在这个循环里面死循环,所以主线程不会因为Looper.loop()里的死循环而导致卡死嘛?那还怎么执行其他操作呢?

  • 在looper启动后主线程上执行的任何代码都是背looper从消息队列里面取出来执行的。

这么死循环下去不会消耗CPU资源吗?

  • 在主线程的MessageQueue没有消息时主线程就会阻塞在loop的queue.next()方法中,这时候主线程会释放掉CPU的资源进入休眠状态,在有下个消息来的时候就会唤醒主线程。这套机制是用Linux的pipe/epoll机制实现。

上面部分的主要核心在queue.next()方法中,接下来看看queue.next()方法。

MessageQueue.next()

    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
      //nextPollTimeoutMillis表示nativePollOnce方法在等待nextPollTimeoutMillis后才会返回
        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) {
                    // 循环查找一条异步的消息
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        // 有消息但是还没有运行到的时候,比如postDelay,计算出离执行时间还有多久并赋值给nextPollTimeoutMillis,表示nativePollOnce方法在等待nextPollTimeoutMillis后返回
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // 取到消息
                        mBlocked = false;
                      //链表操作,获取Message并删除该节点
                        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 {
                    // 没有消息nextPollTimeoutMillis复位
                    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;
        }
    }

Handler

    public Handler() {
        this(null, false);
    }

   public Handler(@Nullable Callback callback, boolean async) {
     //如果不是Static发出可能出现内存泄露的警告
        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
        mLooper = Looper.myLooper();
        if (mLooper == null) {//如果为空提示没有调用Looper.prepare()
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
     		//获取Looper的MessageQueue(消息队列)
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

使用Handler发送消息

handler.sendMessage(message);//发送消息
handler.sendEmptyMessage(0);//发送空消息
handler.sendMessageDelayed(message, 1000);//发送延时消息
handler.sendEmptyMessageDelayed(0, 1000);//发送空的延时消息
handler.sendMessageAtTime(message, System.currentTimeMillis() + 1000);//发送延时1s的消息
handler.post(runnable);

上述方法最终会调用enqueueMessage

Handler.enqueueMessage

    private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
            long uptimeMillis) {
      //设置message的target为当前的Handler
        msg.target = this;
        msg.workSourceUid = ThreadLocalWorkSource.getUid();

        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
      //调用MessageQueue的enqueueMessage方法,将消息放入队列
        return queue.enqueueMessage(msg, uptimeMillis);
    }

接下来看看MessageQueue的enqueueMessage

MessageQueue.enqueueMessage

boolean enqueueMessage(Message msg, long when) {
  //获取消息的target即handler,如果为空发出异常,即消息必须要有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);
            msg.recycle();
            return false;
        }

        msg.markInUse();
      //when表示此消息的执行时间,队列按照收到的消息执行时间来排序
        msg.when = when;
        Message p = mMessages;
        boolean needWake;
        if (p == null || when == 0 || when < p.when) {
            // p为空即当前消息头为空,因为没有消息主线程会阻塞,现在收到了消息所以需要唤醒主线程
            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;
          //将消息放入到队列的准确的位置,链表按msg的when来排序的
            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.
      //如果需要唤醒Looper线程就调用nativeWake方法进行唤醒线程。
        if (needWake) {
            nativeWake(mPtr);
        }
    }
    return true;
}

再看一下Handler的dispatch Message方法

    public void dispatchMessage(@NonNull Message msg) {
      //如果callback不为空调用handleCallback
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
          //最后调用handleMessage
            handleMessage(msg);
        }
    }

总结

调用Handler的各个send、sendXXXXpost、postXXX方法时最终会调用HandlerenqueMessageHandler的enqueMessage调用MessageQueue的enequeMessage,在消息队列的这个方法里面会将Message按实际执行时间插入消息队列(即单链表),并在需要唤醒线程的时候调用nativeWake方法唤醒在next方法里面使用nativePollOnce方法阻塞进入休眠的线程。

Looper在Looper.loop()方法里面通过死循环保证主线程不会运行完任务就会停止,并调用当前Looper的MessageQueue的next方法获取下一条Message,next方法中如果没有消息会调用native层的方法让主线程阻塞进行休眠,减少CPU不必要的占用率,如果获取到Message会调用这个message.target.dispatchMessage方法进行消息分发,优先判断Message的callBack是否存在,如果存在运行callBack的run方法,如果不存在判断target的callBack存不存在,存在的话调用handle的callback的handleMessage并看返回值是否为true来决定是否调用Handler的handleMessage,如果next方法返回null也就表示主线程也该结束了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值