转载请标明出处:一片枫叶的专栏
上一篇文章中我们讲解了AsyncTast的基本使用以及实现原理,我们知道AsyncTask内部是通过线程池和Handler实现的,通过对线程池和handler的封装实现了对异步任务操作。更多关于AsyncTask相关的内容,可参考我的android源码解析之(三)–>异步任务AsyncTask
本文我们将讲解HandlerThread相关的概念。HandlerThread是什么东西呢?了解一个类最好的方法就是查看类的定义,所以我们就看一下HandlerThread是如何定义的吧。查看类的定义时有这样一段话:
Handy class for starting a new thread that has a looper.
The looper can then be used to create handler classes.
Note that start() must still be called.
意思就是说:这个类的作用是创建一个包含looper的线程。
那么我们在什么时候需要用到它呢?加入在应用程序当中为了实现同时完成多个任务,所以我们会在应用程序当中创建多个线程。为了让多个线程之间能够方便的通信,我们会使用Handler实现线程间的通信。这个时候我们手动实现的多线程+Handler的简化版就是我们HandlerThrea所要做的事了。
下面我们首先看一下HandlerThread的基本用法:
/**
* 测试HandlerThread的基本使用
*/
HandlerThread mHandlerThread = new HandlerThread("myHandlerThreand");
mHandlerThread.start();
final Handler mHandler = new Handler(mHandlerThread.getLooper()) {
@Override
public void handleMessage(Message msg) {
Log.i("tag", "接收到消息:" + msg.obj.toString());
}
};
title = (TextView) findViewById(R.id.title);
title.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Message msg = new Message();
msg.obj = "11111";
mHandler.sendMessage(msg);
msg = new Message();
msg.obj = "2222";
mHandler.sendMessage(msg);
}
});
我们首先定义了一个HandlerThread对象,是直接通过new的方式产生的,查看其构造方法:
public HandlerThread(String name) {
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
}
可以知道HandlerThread继承于Thread,所以说HandlerThread本质上是一个线程,其构造方法主要是做一些初始化的操作。
然后我们调用了mHandlerThread.start()方法,由上我们知道了HandlerThread类其实就是一个Thread,一个线程,所以其start方法内部调用的肯定是Thread的run方法,我们查看一下其run方法的具体实现:
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
我们发现其内部调用了Looper.prepate()方法和Loop.loop()方法,熟悉android异步消息机制的童鞋应当知道,在android体系中一个线程其实是对应着一个Looper对象、一个MessageQueue对象,以及N个Handler对象,具体可参考:android源码解析之(二)–>异步消息机制
所以通过run方法,我们可以知道在我们创建的HandlerThread线程中我们创建了该线程的Looper与MessageQueue;
这里需要注意的是其在调用Looper.loop()方法之前调用了一个空的实现方法:onLooperPrepared(),我们可以实现自己的onLooperPrepared()方法,做一些Looper的初始化操作;
run方法里面当mLooper创建完成后有个notifyAll(),getLooper()中有个wait(),这是为什么呢?因为的mLooper在一个线程中执行,而我们的handler是在UI线程初始化的,也就是说,我们必须等到mLooper创建完成,才能正确的返回getLooper();wait(),notify()就是为了解决这两个线程的同步问题
然后我们调用了:
final Handler mHandler = new Handler(mHandlerThread.getLooper()) {
@Override
public void handleMessage(Message msg) {
Log.i("tag", "接收到消息:" + msg.obj.toString());
}
};
该Handler的构造方法中传入了HandlerThread的Looper对象,所以Handler对象就相当于含有了HandlerThread线程中Looper对象的引用。
然后我们调用handler的sendMessage方法发送消息,在Handler的handleMessge方法中就可以接收到消息了。
最后需要注意的是在我们不需要这个looper线程的时候需要手动停止掉;
protected void onDestroy() {
super.onDestroy();
mHandlerThread.quit();
}
好了,以上就是HandlerThread相关的知识了,相对来说HandlerThread还是比较简单的,其本质上就是一个Thread线程,只不过里面包含了Looper和MessageQueue,最后我们在这里总结一下。
总结:
HandlerThread本质上是一个Thread对象,只不过其内部帮我们创建了该线程的Looper和MessageQueue;
通过HandlerThread我们不但可以实现UI线程与子线程的通信同样也可以实现子线程与子线程之间的通信;
HandlerThread在不需要使用的时候需要手动的回收掉;
另外对android源码解析方法感兴趣的可参考我的:
android源码解析之(一)–>android项目构建过程
android源码解析之(二)–>异步消息机制
android源码解析之(三)–>异步任务AsyncTask
本文以同步至github中:github.com/yipianfengy…,欢迎star和follow
转载请标明出处:一片枫叶的专栏
上一篇文章中我们讲解了android项目的构件流程,apk文件的生成过程,其实只要是记住那那张构建图基本上就对apk构建流程有了大概的了解了,更多关于apk构建流程的知识点可以参考我的:android源码解析之(一)–>android项目构建过程
前段时间在知乎上看了一篇非常不错的博文:有没有必要阅读ANDROID源码
痛定思过,为了更好的深入android体系,决定学习android framework层源码,就从最简单的android异步消息机制开始吧。所以也就有了本文:android中的异步消息机制。本文主要从源码角度分析android的异步消息机制。
(一)Handler的常规使用方式
/**
* 测试Activity,主要用于测试异步消息(Handler)的使用方式
*/
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
private TextView texttitle = null;
/**
* 在主线程中定义Handler,并实现对应的handleMessage方法
*/
public static Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 101) {
Log.i(TAG, "接收到handler消息...");
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
texttitle = (TextView) findViewById(R.id.texttitle);
texttitle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread() {
@Override
public void run() {
mHandler.sendEmptyMessage(101);
}
}.start();
}
});
}
}
可以看出,一般handler的使用方式都是在主线程中定义Handler,然后在子线程中调用mHandler.sendEmptyMessage();方法,然么这里有一个疑问了,我们可以在子线程中定义Handler么?
(二)如何在子线程中定义Handler?
我们在子线程中定义Handler,看看结果:
/**
* 定义texttitle的点击事件处理
*/
texttitle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/**
* 定义在子线程中执行handler的创建
*/
new Thread() {
@Override
public void run() {
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 101) {
Log.i(TAG, "在子线程中定义Handler,并接收到消息。。。");
}
}
};
}
}.start();
}
});
点击按钮并运行这段代码:
可以看出来在子线程中定义Handler对象出错了,难道Handler对象的定义或者是初始化只能在主线程中?
其实不是这样的,错误信息中提示的已经很明显了,在初始化Handler对象之前需要调用Looper.prepare()方法,那么好了,我们添加这句代码再次执行一次:
/**
* 定义texttitle的点击事件处理
*/
texttitle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread() {
@Override
public void run() {
Looper.prepare();
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 101) {
Log.i(TAG, "在子线程中定义Handler,并接收到消息。。。");
}
}
};
}
}.start();
}
});
再次点击按钮执行该段代码之后,程序已经不会报错了,那么这说明初始化Handler对象的时候我们是需要调用Looper.prepare()的,那么主线程中为什么可以直接初始化Handler呢?
其实不是这样的,在App初始化的时候会执行ActivityThread的main方法:
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())
AndroidKeyStoreProvider.install()
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId())
TrustedCertificateStore.setDefaultUserDirectory(configDir)
Process.setArgV0("")
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")
}
可以看到原来Looper.prepare()方法在这里调用了,所以在其他地方我们就可以直接初始化Handler了。
并且我们可以看到还调用了:Looper.loop()方法,通过参考阅读其他文章我们可以知道一个Handler的标准写法其实是这样的:
Looper.prepare();
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 101) {
Log.i(TAG, "在子线程中定义Handler,并接收到消息。。。");
}
}
};
Looper.loop();
(三)查看Handler源码
1)查看Looper.prepare()方法
static final ThreadLocal sThreadLocal = new ThreadLocal();
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
public static void prepare() {
prepare(true);
}
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));
}
可以看到Looper中有一个ThreadLocal成员变量,熟悉JDK的同学应该知道,当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。具体参考:彻底理解ThreadLocal
由此可以看出在每个线程中Looper.prepare()能且只能调用一次,这里我们可以尝试一下调用两次的情况。
/**
* 这里Looper.prepare()方法调用了两次
*/
Looper.prepare();
Looper.prepare();
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 101) {
Log.i(TAG, "在子线程中定义Handler,并接收到消息。。。");
}
}
};
Looper.loop();
再次运行程序,点击按钮,执行该段代码:
可以看到程序出错,并提示prepare中的Excetion信息。
我们继续看Looper对象的构造方法,可以看到在其构造方法中初始化了一个MessageQueue对象:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
综上小结(1):Looper.prepare()方法初始话了一个Looper对象并关联在一个MessageQueue对象,并且一个线程中只有一个Looper对象,只有一个MessageQueue对象。
2)查看Handler对象的构造方法
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class 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;
}
可以看出在Handler的构造方法中,主要初始化了一下变量,并判断Handler对象的初始化不应再内部类,静态类,匿名类中,并且保存了当前线程中的Looper对象。
综上小结(2):Looper.prepare()方法初始话了一个Looper对象并关联在一个MessageQueue对象,并且一个线程中只有一个Looper对象,只有一个MessageQueue对象。而Handler的构造方法则在Handler内部维护了当前线程的Looper对象
3)查看handler.sendMessage(msg)方法
一般的,我们发送异步消息的时候会这样调用:
mHandler.sendMessage(new Message());
通过不断的跟进源代码,其最后会调用:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
原来msg.target就是Handler对象本身;而这里的queue对象就是我们的Handler内部维护的Looper对象关联的MessageQueue对象。查看messagequeue对象的enqueueMessage方法:
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p;
prev.next = msg;
}
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
可以看到这里MessageQueue并没有使用列表将所有的Message保存起来,而是使用Message.next保存下一个Message,从而按照时间将所有的Message排序;
4)查看Looper.Loop()方法
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the 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;
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
Message msg = queue.next();
if (msg == null) {
return;
}
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(msg);
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
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();
}
}
可以看到方法的内容还是比较多的。可以看到Looper.loop()方法里起了一个死循环,不断的判断MessageQueue中的消息是否为空,如果为空则直接return掉,然后执行queue.next()方法:
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
可以看到其大概的实现逻辑就是Message的出栈操作,里面可能对线程,并发控制做了一些限制等。获取到栈顶的Message对象之后开始执行:
msg.target.dispatchMessage(msg)
那么msg.target是什么呢?通过追踪可以知道就是我们定义的Handler对象,然后我们查看一下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);
}
}
可以看到,如果我们设置了callback(Runnable对象)的话,则会直接调用handleCallback方法:
private static void handleCallback(Message message) {
message.callback.run();
}
即,如果我们在初始化Handler的时候设置了callback(Runnable)对象,则直接调用run方法。比如我们经常写的runOnUiThread方法:
runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
看其内部实现:
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
而如果msg.callback为空的话,会直接调用我们的mCallback.handleMessage(msg),即handler的handlerMessage方法。由于Handler对象是在主线程中创建的,所以handler的handlerMessage方法的执行也会在主线程中。
总结:
1)主线程中定义Handler,直接执行:
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
而如果想要在子线程中定义Handler,则标准的写法为:
Looper.prepare();
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
Looper.loop();
2)一个线程中只存在一个Looper对象,只存在一个MessageQueue对象,可以存在N个Handler对象,Handler对象内部关联了本线程中唯一的Looper对象,Looper对象内部关联着唯一的一个MessageQueue对象。
3)MessageQueue消息队列不是通过列表保存消息(Message)列表的,而是通过Message对象的next属性关联下一个Message从而实现列表的功能,同时所有的消息都是按时间排序的。
4)android中两个子线程相互交互同样可以通过Handler的异步消息机制实现,可以在线程a中定义Handler对象,而在线程b中获取handler的引用并调用sendMessage方法。
5)activity内部默认存在一个handler的成员变量,android中一些其他的异步消息机制的实现方法:
Handler的post方法:
mHandler.post(new Runnable() {
@Override
public void run() {
}
});
查看其内部实现:
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
可以发现其内部调用就是sendMessage系列方法。。。
view的post方法:
public boolean post(Runnable action) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.post(action);
}
ViewRootImpl.getRunQueue().post(action);
return true;
}
可以发现其调用的就是activity中默认保存的handler对象的post方法。
activity的runOnUiThread方法:
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
判断当前线程是否是UI线程,如果不是,则调用handler的post方法,否则直接执行run方法。
参考文章:
Android异步消息处理机制完全解析,带你从源码的角度彻底理解
Android异步消息处理机制详解及源码分析
另外对android源码解析方法感兴趣的可参考我的:
android源码解析之(一)–>android项目构建过程
本文以同步至github中:github.com/yipianfengy…,欢迎star和follow