您的位置:首页 > 运维架构

Looper

2015-11-29 21:38 239 查看
activity/service启动时,会启动三个线程。一个主线程和两个Binder线程

主线程在ActivityThread的main方法中启动
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());
AndroidKeyStoreProvider.install();
// 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>");
<span style="color:#ff0000;">Looper.prepareMainLooper();</span>
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
<span style="color:#ff0000;">sMainThreadHandler = thread.getHandler();</span>
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
<span style="color:#ff0000;">Looper.loop();</span>
throw new RuntimeException("Main thread loop unexpectedly exited");
}


顺藤摸瓜,我们先去看看Looper.prepareMainLooper()方法

/**
* Initialize the current thread as a looper, marking it as an
* application's main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself.  See also: {@link #prepare()}
* <span style="color:#3333ff;">初始化当前线程作为looper对象,标记它作为应用程序的main looper。这个main looper 是android自动为你创建的,所以你永远不需要调用这个方法。</span>
*/
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
<span style="color:#ff0000;">sMainLooper = myLooper();</span>
}
}
根据方法的注释我们可以看到,这个是由系统调用的。并且不建议我们自行调用。

在这个方法中又调用到了prepare方法,我们进去看看

/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
* 初始化当前线程作为looper对象。这个给你一个机会可以在真正启动一个loop之前去创造handlers并且与looper对象建立关联。
<span style="white-space:pre">	</span>确保你调用了loop()方法,在调用prepare()方法之后。
*/
public static void prepare() {
prepare(true);
}

private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
<span style="color:#cc0000;">sThreadLocal.set(new Looper(quitAllowed));</span>
}
很明显,在prepare方法中,创建了一个Looper对象,并且在Looper的构造函数里,创建了MessageQueue对象,并赋值给了mQueue这个成员变量。再去看看sThreadLocal这个变量

//  sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();


明显可以看到,这个变量是用来存Looer对象的,而且在prepare中完成了set赋值操作,所以注释说,get方法会返回null,如果没有调用prepare方法。

ok,这里可以为prepareMainThread做个小总结了。简单一句话:

创建一个与主线程相关联的Looper对象,并且存入sThreadLocal中。

咱们继续往下看Looper.loop()方法

/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
* <span style="color:#3333ff;">在线程中启动Message队列。</span>
*/
public static void loop() {
<span style="color:#ff0000;">final Looper me = myLooper();</span>
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
<span style="color:#ff0000;"> final MessageQueue queue = me.mQueue;</span>

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

<span style="color:#ff0000;"> for (;;) {</span>
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
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}

<span style="color:#ff0000;">msg.target.dispatchMessage(msg);</span>

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


ok,loop方法比较长,咱们一点一点分析,先看myLooper()
/**
* Return the Looper object associated with the current thread.  Returns
* null if the calling thread is not associated with a Looper.
* <span style="color:#3366ff;">返回与</span><span style="color:#993399;">当前线程</span><span style="color:#3366ff;">相关联的Looper对象。  如果调用的线程没有和一个Looper相关联则返回null</span>
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}

代码很简单,就是从sThreadLocal中取出looper对象,因为之前sThreadLocal已经将与当前线程通过set方法存入了,所以返回值不会为null

接下来继续看MessageQueue queue = me.mQueue这行代码

先分析一个,这行代码的意思应该是将Looper对象中的messageQueue对象的内存地址赋值给当前prepare中创建的Looper中的MessageQueue对象

继续看一下for(,,)

这是一个死循环,从队列中不停的取出Message,如果没有直接返回如果有Message,则调用该Message对象的

这里可以做一个总结了:

Looper的创建以及与之绑定的MessageQueue关系已经明朗,它们之间是一对一的关系

继续向下看

target.dispatcher(msg)方法

target是Handler对象,也是Message的成员变量,我们一起看一下它是如何被赋值的,到底是与谁相关联的呢?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: