一、Android Handler的常见用法
在Android代码中Handler常见的逻辑是在UI线程中创建一个Handler变量mHander,传递到非UI线程逻辑中,在非UI线程中通过它来更新UI界面中的逻辑值。
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
String text = (String) msg.obj;
tishi.setText(text);
super.handleMessage(msg);
}
};
class HandlerTestRunnable implements Runnable {
private Handler mHandler;
public HandlerTestRunnable(Handler handler) {
mHandler = handler;
}
@Override
public void run() {
// TODO Auto-generated method stub
Message msg = new Message();
msg.obj = "refresh UI element";
mHandler.sendMessage(msg);
}
}
new Thread(new HandlerTestRunnable(mHandler)).start();
二、Handler的源码解读
在上面的逻辑中可以看到在UI的线程逻辑中new了一个Handler变量,并重写了它的handleMeaasge方法。查阅源码逻辑,对Handler的操作进行如下分析:
1.Handler的构建
public Handler() {
this(null, false);
}
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;
}
在handler的构建过程中会初始化两个很重要的变量,mLooper和mQueue。mLooper是线程的消息循环, Looper.myLooper()获取的本线程的消息循环,mQueue是Looper对象携带的一个消息队列。在上面的示例代码中 callback和async分别被置为null和false。
2.消息的发送
在调用Handler的sendMessage(Message msg)之后,消息最终会在enqueueMessage方法中插入到消息队列中。
//Handler的enqueueMessage方法
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
3、消息的读取和执行
在UI的主线程启动的最后会执行Looper.loop。
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());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
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.loop的逻辑中,或获取本线程的MessageQueue,并执行存储在其中的消息。
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
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);
}
// 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();
}
}
msg.target.dispatchMessage(msg)执行消息分发和处理,target是一个Handler对象的变量。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
回到之前的逻辑,在UI线程中定义Handler时,重新了handleMessage方法,另外消息的callback变量被定义为空。因此在子线程中通过UI线程传递的Handler变量发送消息最终都会被UI线程的逻辑处理。
三、Handler的特应用
在线程中调用Toast会弹出如下错误:
Can’t create handler inside thread that has not called Looper.prepare()
这是因为在子线程的ThreadLoacl中没有设置过Looper,所以会抛出异常,一种解决办法是将显示Toast放入到UI线程中去显示。
private class ShowToast implements Runnable {
private String mContent;
public ShowToast(String textParam) {
mContent = textParam;
}
@Override
public void run() {
Toast.makeText(mContext, mContent, 0).show();
}
}
mHandler.post(new ShowToast("the content to show"));