Camera安卓源码剖析-源码中的线程沟通实例

来源:互联网 发布:官方mac os 10.9.5 编辑:程序博客网 时间:2024/05/17 13:46

主要涉及到了Executor,Handler,Looper,MessageQueue的概念。

Step1

在这上一篇文章中的观察者模式中subject调用onSurfaceTextureAvailable()方法中会调用另外一个方法:

CaptureModule.javapublic class CaptureModule{    private void reopenCamera() {        if (mPaused) {            return;        }        AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {            @Override            public void run() {                closeCamera();                if(!mAppController.isPaused()) {                    openCameraAndStartPreview();                }            }        });    }}

在此方法中会采用AsyncTask中的Executor进行并行操作,他是一个线程池,调用该线程池的execute方法并传入一个runnable就可以执行该runnable的run方法看这里关于线程池的介绍。

AsyncTask.javapublic abstract class AsyncTask<Params, Progress, Result> {.../*** An {@link Executor} that can be used to execute tasks in parallel.*/public static final Executor THREAD_POOL_EXECUTOR;    static {        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(                CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,                sPoolWorkQueue, sThreadFactory);        threadPoolExecutor.allowCoreThreadTimeOut(true);        THREAD_POOL_EXECUTOR = threadPoolExecutor;    }...}

在进入异步操作后调用openCameraAndStartPreview();

Step2

openCameraAndStartPreview();方法体中,执行:

MainThread mainThread = MainThread.create();

进入MainThread类源码:

public class MainThread extends HandlerExecutor {    private MainThread(Handler handler) {        super(handler);    }    public static MainThread create() {        return new MainThread(new Handler(Looper.getMainLooper()));    }}

可以在代码中发现,先new了一个Handler,此Handler中传入了一个Looper,此Looper其实是主线程的Looper。
而MainThread其实是一个Executor,执行其execute()方法会执行Handler.post(Runnable)。 接下来介绍Handler&Looper&MessageQueue的概念。

一. Looper&MessageQueue

一个线程拥有一个Handler,一个Handler拥有一个Looper, 每个Looper拥有一个MessageQueue。

  • 以下的代码中,线程创建时会调用Looper的prepare()方法,创建一个Looper实例,并保存到实例中的sThreadLocal中。 如果是主线程(UI线程)的话,会调用prepareMainLooper()方法,将主线程的Looper保存到静态变量 sMainLooper中。这样任何时候想获取主线程的Looper就可以通过静态量sMainLooper获取。
public final class Looper {    //全局变量    private static Looper sMainLooper;    // sThreadLocal.get() will return null unless you've called prepare().    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<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));    }    /**     * 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() {        prepare(false);        synchronized (Looper.class) {            if (sMainLooper != null) {                throw new IllegalStateException("The main Looper has already been prepared.");            }            sMainLooper = myLooper();        }    }    public static @Nullable Looper myLooper() {        return sThreadLocal.get();    }}
  • prepare完成后会调用loop()方法启动该线程的loop死循环操作。
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(); // 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 {                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);            }            msg.recycleUnchecked();        }    }

二. Handler

Handler会与Looper中的MessageQueue绑定,之后可以向MessageQueue中sendMessage,Looper会不断的从MessageQueue中取出message并执行message.target.dispatchMessage()

之前介绍了Looper及其内部的MessageQueue,接下来介绍Handler的概念。

public class Handler {    public interface Callback {        public boolean handleMessage(Message msg);    }    public void handleMessage(Message msg) {    }    public void dispatchMessage(Message msg) {        if (msg.callback != null) {            handleCallback(msg);        } else {            if (mCallback != null) {                if (mCallback.handleMessage(msg)) {                    return;                }            }            handleMessage(msg);        }    }    public Handler(Looper looper, Callback callback, boolean async) {        mLooper = looper;        mQueue = looper.mQueue;        mCallback = callback;        mAsynchronous = async;    }    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);    }    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {        msg.target = this;        if (mAsynchronous) {            msg.setAsynchronous(true);        }        return queue.enqueueMessage(msg, uptimeMillis);    }}

可以在上述代码的构造函数中发现,mQueue = looper.mQueue;,也就是将Handler与Looper中的MessageQueue绑定。而只要绑定了此MessageQueue,Handler就可以调用sendMessage(Message msg), 此方法最后会调用上述源码中的sendMessageAtTime(Message msg, long uptimeMillis),可以看到在此方法中会将msg入MessageQueue队列。 而在enqueueMessage()中会将msg的target设为此Handler自身msg.target=this,至此,双向绑定完成。

这里写图片描述

三. 总结

也就是说MainThread的创建的作用就是可以异步并发处理UI线程中的事件。 由于目前的所有操作均发生在不同于主线程的并发线程中,所有在此拥有了MainThread我们就可以指使主线程做相应的操作

原创粉丝点击