Android的异步处理消息机制

本文主要介绍Android的异步处理消息机制


知识点:

1. 主线程:既要处理UI事件,又要处理后台服务等工作,忙不过来的。为了解决这个问题,就有了多线程,主线程可以通过创建多个子线程来处理后台服务、和一些耗时工作,自身一心一意处理UI事件。
2. Handler和Message:大家都知道,handler主要用在子线程中发送消息通知UI线程更新UI的。线程间的通讯通过handler.sendMessage()和handler.handleMessage(Message msg)来实现。
3. Looper:Looper就是循环的意思,它的任务是从消息队列取出任务交给消息的目标处理。
4. 消息队列的工作机制:Handler中有一个Looper,Looper中有一个消息队列。每当我们用Handler去发送消息,消息就会放置Looper中的消息队列里边,然后Looper会去取出对应的消息去发给对应的target去处理,即Handler,所以调用了handler的 dispatchMessage方法。

接下来上源码解析:


handler.sendMessage(msg)的过程

 public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }
 public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
 public boolean sendMessageAtTime(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);
    }
当handler. sendMessage( msg )之后,我们可以看到最后一个代码行 enqueueMessage,这里是把新的Message加入消息队列中,即加入到Looper中消息队列。然而,

Looper是如何运作的呢?

public static void loop() {
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        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(); // 这里在消息队列中取出消息,如为空就会阻塞了。
            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);
            }
            msg.target.dispatchMessage(msg);    // 这里调用了消息目标的dispatchMessage方法,即Handler的dispatchMessage方法
            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.recycle();
        }
    }


Handler是如何dispatchMessage的:

/**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

msg.callback是个什么玩意呢?

其实他就是一个线程,有两种方式,new Handler(callback),handler.post(callback),相信大家对这2种方式都不陌生。至此,消息处理的机制大致已经了解了,然后我们了解下Handler的创建的一些注意点:


在子线程中创建Handler会报错:

public class MainActivity extends Activity {
 
 private Handler handlerA;
 
 private Handler handlerB;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
 
  handlerA = new Handler();
 
  new Thread(new Runnable() {
   
   @Override
   public void run() {
    handlerB = new Handler();
   }
  }).start();
 
 }
 
}
运行一下程序,闪退了,可以看到Logcat,抛出了“ Can't create handler inside thread that has not called Looper.prepare()”的异常。


这是为什么报错呢?

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

        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }
这里我们看到了,在构造函数中有对Looper的判空操作,这就能看出原因了,原来在子线程中创建的Handler是没有Looper对象的。这是为啥莫呢,主线程有,这里却木有。我们接着往下看:

public static Looper myLooper() {
        return sThreadLocal.get();
    }
sThreadLocal显然不存在looper,那么我要在哪儿设置这个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));
    }
可以看出,子线程中并没有调用prepare方法,而主线程中是调用了的,回归到ActivityThread的main方法中,让我们看看真伪:

public static void main(String[] args) {
    SamplingProfilerIntegration.start();
    CloseGuard.setEnabled(false);
    Environment.initForCurrentUser();
    EventLogger.setReporter(new EventLoggingReporter());
    Process.setArgV0("<pre-initialized>");
    Looper.prepareMainLooper();    // 这里会再调用Looper.prepare()方法
    ActivityThread thread = new ActivityThread();
    thread.attach(false);
    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }
    AsyncTask.init();
    if (false) {
        Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread"));
    }
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

public static final void prepareMainLooper() {
    prepare();
    setMainLooper(myLooper());
    if (Process.supportsProcesses()) {
        myLooper().mQueue.mQuitAllowed = false;
    }
}

在主线程调用prepareMainLooper的时候就已经用了prepare方法生成了Looper,就是说在主线程中可以直接创建Handler对象,而在子线程中需要先调用Looper.prepare()才能创建Handler对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值