1)知识点
A. Handler主要包含处理消息入口函数handleMessage(用于对象实现之)、获取消息函数(obtainMessage)、发消息函数(sendMessage、post)。Handler操作的消息来自于消息队列,该队列是由Handler所在线程初始化时创建的,并位于Looper下。
B. 消息分为两类:
a. 命令消息,使用sendMessageXXX发送,由dispatchMessage-->handleMessage接收处理;
b. 动作消息,使用postXXX发送,由dispatchMessage-->“msg->callback”接收处理。
C. 注册处理消息的操作有三种方法:
a. 实现Handler类的handleMessage函数;
b. 实现一个closure或者runnable,调用post发送之;
c. 构造Handler对象时使用Handler(looper, callback),其中第二个参数为回调函数。
D. Handler绑定Looper有两种方法:
b. 创建Handler对象时调用构造函数:Handler(looper);
a. 直接调用无参数Handler构造函数,且当前线程中存在Looper::prepare()、Looper::loop()
E. Looper使用方法:
Looper::prepare();//保证当前线程唯一性并创建消息队列
xxx = Looper::myLooper(); //获取looper对象
Looper::loop();//开始接收处理消息
E. AsyncTask任务实现原理
AsyncTask实现了异步任务类,本质上就是“线程+消息队列+条件变量”。定义一个异步任务子类,其中实现任务执行等函数(如doInBackground),然后确定任务执行方式(execute OR executeOnExecutor),最后调用execute即可。AsyncTask内部自建的消息队列传递的都是动作消息。最重要的两个成员变量:WorkerRunnable--子线程执行函数,InternalHandler--主线程处理子线程回复消息的Handler。
单线程消息流:
execute ->>
HandlerThread.execute ->>
[子线程]WorkerRunnable.run->>
[子线程]doInBackground+发送ON_POST_EXECUTE_MESSAGE->>
InternalHandler.handleMessage
线程池消息流:
executeOnExecutor->>
ThreadPoolExecutor.execute->>
[子线程]ThreadPoolExecutor::WorkerThread.run->>
[子线程]WorkerRunnable.run->>
[子线程]doInBackground+发送ON_POST_EXECUTE_MESSAGE->>
InternalHandler.handleMessage
F. AsyncTask使用方法
a. 定义AsyncTask子类,实现onPreExecute、doInBackground、onProgressUpdate、onPostExecute、onCancelled函数
b. 启动任务,调用execute(创建子线程)或executeOnExecutor(调用线程池中线程)