深入探索Android消息机制之Handler,为什么我们能在

作者:金沙娯乐场手机版

各类Handler 的线程皆有三个 Looper ,主线程当然也不例外,然则大家从未计划过主线程的 Looper 而能够一向运用,那是干什么?

早先写了一篇关于Message的篇章,感兴趣的爱侣能够去看一下【Android音信机制之Message分析(面试)】,这一遍我们来聊一下新闻机制中用得最多的Handler,也是面试中问得最多的之一,在此地自个儿先抛多少个难题出来:

瞩目:平日我们感觉 ActivityThread 正是主线程。事实上它并不是叁个线程,而是主线程操作的长官,所以啊,作者认为把 ActivityThread 认为正是主线程未有可过分责骂,此外主线程也得以说成 UI 线程。

1.Handler、Looper、Thread有什么关系?
2.怎么在子线程创立handler会抛非常 "Can't create handler inside thread that has not called Looper.prepare(State of Qatar"?
3.怎么行使handler来处理message?
4.为什么不能够在子线程更新UI?

在 ActivityThread.main(State of Qatar 方法中犹如下代码: 1//android.app.ActivityThread

咱俩带着主题材料去看源码:

2public static void main(String[] args) {

世家先对一下的目的,脑补一下厂子的气象:

3 //...

Handler:音信的管理者,工厂中流水生产线的老工人。
Message:系统传递的音信,工厂中流水生产线上的成品。
MessageQueue:新闻队列,工厂中流水生产线上的传递带。
Looper:内燃机,工厂中使流水生产线的传递带移动的发动机。

4 Looper.prepareMainLooper();

大家先从程序入口来开展剖析,Android应用程序的入口在ActivityThread的main函数中,大家先从main函数举行分析:

5

ActivityThread.java:

6 ActivityThread thread = new ActivityThread();

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>");

    //在android应用程序的入口其实在ActivityThread的main方法
    //在这里,主线程会创建一个Looper对象。
    Looper.prepareMainLooper();

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

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

7 thread.attach;

代码相当长,大家挑关键的代码来看,在代码中作者已写上讲解,在main函数中,Looper调用了prepareMainLooer(State of Qatar,大家再踏入Looper看看。

8

Looper.java:

9 if (sMainThreadHandler == null) {

/**
 * 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()}
 */
public static void prepareMainLooper() {
    //在主线程中,其默认初始化一个Looper对象,因此我们在主线程的操作中是不需要自己去调prepare()。
    prepare(false);
    synchronized (Looper.class) {
        //这里先进行判断,在主线程是否已经存在Looper了,
        // 避免我们手动去调用prepareMainLooper(),因为这个是给程序入口初始化的时候系统会自动调用的
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        //设置全局变量,主线程的looper
        sMainLooper = myLooper();
    }
}

10 sMainThreadHandler = thread.getHandler();

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.

11 }

瞩目这么些函数的评释,大概意思是:在主线程创立三个looper,是其一主线程的主looper,当以此app在初叶化的时候就能够自行创造,由此那么些函数不是给您们调用的,是给系统自个儿在程序成立的时候调用的。

12 //...

小编们世袭往下看,有个prepare(boolean卡塔尔(قطر‎函数,我们去探问那些到底是用来干什么的。
Looper.java:

13 Looper.loop();

private static void prepare(boolean quitAllowed) {
    //先判断当前线程是否已经存在Looper了,如果存在,不允许设置新的Looper对象,一个线程只允许存在一个Looper
    if (sThreadLocal.get() != null) {
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    //在当前线程中,创建新的Looper对象,并绑定当前线程
    sThreadLocal.set(new Looper(quitAllowed));
}

14

在那处,大家来看了sThreadLocal,我们先看看那些sThreadLocal在Looper是为啥用的。

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

Looper.java:

16}

// sThreadLocal.get() will return null unless you've called prepare().
//sThreadLocal在Looper中作为全局变量,用于保存每个线程中的数据,可以看做是容器
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

Looper.prepareMainLooper(卡塔尔国; 代码如下: 1/**

Looper中,sThreadLocal作为三个全局变量,sThreadLocal其实是保留Looper的一个容器,我们后续往ThreadLocal的get、set实行解析。

2 * Initialize the current thread as a looper, marking it as an

澳门金沙线上娱乐,ThreadLocal.java:

3 * application's main looper. The main looper for your application

/**
 * Returns the value in the current thread's copy of this
 * thread-local variable.  If the variable has no value for the
 * current thread, it is first initialized to the value returned
 * by an invocation of the {@link #initialValue} method.
 *
 * @return the current thread's value of this thread-local
 */
public T get() {
    //获取当前线程保存的对象--通过get函数来获取Looper对象
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null)
            return (T) e.value;
    }
    return setInitialValue();
}

/**
 * Sets the current thread's copy of this thread-local variable
 * to the specified value.  Most subclasses will have no need to
 * override this method, relying solely on the {@link #initialValue}
 * method to set the values of thread-locals.
 *
 * @param value the value to be stored in the current thread's copy of
 *              this thread-local.
 */
public void set(T value) {
    //把当前的looper保存到当前线程中
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}

4 * is created by the Android environment, so you should never need

我们来看关键的代码:
Thread t=Thread.currentThread();

5 * to call this function yourself. See also: {@link #prepare()}

也正是说,大家的Looper对象分别保存在相呼应的线程中。大家看回来大家的prepare(boolean卡塔尔函数:
looper.java:

6 */

private static void prepare(boolean quitAllowed) {
    //先判断当前线程是否已经存在Looper了,如果存在,不允许设置新的Looper对象,一个线程只允许存在一个Looper
    if (sThreadLocal.get() != null) {
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    //在当前线程中,创建新的Looper对象,并绑定当前线程
    sThreadLocal.set(new Looper(quitAllowed));
}

7public static void prepareMainLooper() {

Looper.prepare(boolean卡塔尔(قطر‎的作用正是制造多个Looper对象,并与日前线程绑定在同盟。在代码中,首先推断当前线程是或不是业已存在looper,要是不设有则创设新的looper并且绑定到最近的线程上。

8 prepare;

再看回在此以前的代码:
looper.java:

9 synchronized (Looper.class) {

**
 * 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()}
 */
public static void prepareMainLooper() {
    //在主线程中,其默认初始化一个Looper对象,因此我们在主线程的操作中是不需要自己去调prepare()。
    prepare(false);
    synchronized (Looper.class) {
        //这里先进行判断,在主线程是否已经存在Looper了,
        // 避免我们手动去调用prepareMainLooper(),因为这个是给程序入口初始化的时候系统会自动调用的
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        //设置全局变量,主线程的looper
        sMainLooper = myLooper();
    }
}

10 if (sMainLooper != null) {

分级看一下sMainLooper是什么,myLooper(卡塔尔又是什么?
Looper.java:

11 throw new IllegalStateException("The main Looper has already been prepared.");

//保存一个主线程的looper
private static Looper sMainLooper;  // guarded by Looper.class

/**
 * Return the Looper object associated with the current thread.  Returns
 * null if the calling thread is not associated with a Looper.
 */
public static Looper myLooper() {
    //使用当前线程的looper
    return sThreadLocal.get();
}

12 }

sMainLooper在Looper做为多少个全局变量,保存主线程绑定的looper,myLooper(卡塔尔(قطر‎则是取稳当前线程绑定的Looper。在prepareMainLooper(State of Qatar中,在主线程中创立二个新的Looper,并且绑定主线程中,同有时间把这么些主线程的looper赋值给sMainLooer那几个全局变量。

13 sMainLooper = myLooper();

ActivityThread.java:

14 }

   public static void main(String[] args) {
        ......

        //在android应用程序的入口其实在ActivityThread的main方法
        //在这里,主线程会创建一个Looper对象。
        Looper.prepareMainLooper();

        ......
        ......
        ......        
        //执行消息循环
        Looper.loop();

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

15}

在应用程序ActivityThread.main入口中,系统除去调用Looper.prepareMainLooper,何况在最终还调用了Looper.loop(卡塔尔,那几个函数有啥?大家脑补一下,工厂里的流水线上,除了有传送带外,假若你不让它动起来,那传送带也没怎么效果,那么Looper.loop的法力正是让那一个传送拉动起来,也正是我们的让大家的音讯队列动起来。

能够看来在 ActivityThread 里 调用了 Looper.prepareMainLooper()方法创立了 主线程的 Looper ,何况调用了 loop()方法,所以我们就能够平昔运用 Handler 了。

Looper.java:

瞩目:Looper.loop(卡塔尔 是个死循环,前面包车型大巴代码平常意况不会奉行。

/**
 * 调用此函数用于启动消息队列循环起来,作用相当于工厂流水线中的传送带的开关,
 * 只有把开关打开,传送带才跑起来
 * Run the message queue in this thread. Be sure to call
 * {@link #quit()} to end the loop.
 */
public static void loop() {
    //先进行判断当前线程是否有绑定looper
    final Looper me = myLooper();
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    //获取这个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 (; ; ) {
        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也就是hanlder.看回代码hanlder.enqueueMessage()
            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);
        }
        //最后回收这个message
        msg.recycleUnchecked();
    }
}

本文由金沙误乐游戏发布,转载请注明来源

关键词: 金沙误乐游戏 日记本 能在 而不 主线