计算机技术实战

纸上得来终觉浅,绝知此事要躬行。

Download this project as a .zip file Download this project as a tar.gz file

Handler机制分析

目录

框架图

和上图有关的Message的几个成员变量:

public final class Message implements Parcelable {
    /*package*/ Handler target;

    /*package*/ Runnable callback;

    // sometimes we store linked lists of these things
    /*package*/ Message next;
}

主线程Handler和Looper

public final class ActivityThread extends ClientTransactionHandler {
    final Looper mLooper = Looper.myLooper();
    final H mH = new H();
    static volatile Handler sMainThreadHandler;  // set once in main()
    public static void main(String[] args) {
    	Looper.prepareMainLooper();
    	ActivityThread thread = new ActivityThread();
    	if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        Looper.loop();
    }
    final Handler getHandler() {
        return mH;
    }
    class H extends Handler {
    	// ...
    }
}

AsyncTask的Handler

创建Handler

public abstract class AsyncTask<Params, Progress, Result> {
    private static InternalHandler sHandler;
    private final Handler mHandler;

    public AsyncTask(@Nullable Looper callbackLooper) {
        mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
            ? getMainHandler()
            : new Handler(callbackLooper);
    }

    private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult<Result>(this, result));
        message.sendToTarget();
        return result;
    }

    private Handler getHandler() {
        return mHandler;
    }
}

发送消息

    private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult<Result>(this, result));
        message.sendToTarget();
        return result;
    }