Android 是不容许在子线程中进行 UI 操作的,但是有些时候我们必须在子线程里去执行一些耗时任务,然后根据执行的结果来更新相应的 UI 控件,对于这种情况,Android 提供了一套异步消息处理机制,完美解决了在子线程中进行 UI 相关操作的问题,今天我们就来一起学习一下这个 Android 系统提供的异步消息处理机制,下面是我们学习的内容大纲
一、什么是 Handler
Handler 是 Android 给我们提供的用来更新 UI 的一套机制,也是一套消息处理机制,我们可以通过它发送消息和处理消息
二、如何使用 Handler
首先我们来创建一个 HandlerTest 项目,用来演示 Handler 相关的操作
MainActivity 中的代码如下:
/**
* Handler 测试
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView textView;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
/**
* 响应点击事件
*
* @param v
*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
//点击按钮在子线程中更新 UI
new Thread(new Runnable() {
@Override
public void run() {
textView.setText("world");
}
}).start();
break;
}
}
}代码非常简单,这里我们创建了一个子线程并在子线程中进行 UI 更新,发现程序 Crash 掉,报出如下错误:
这就是说着子线程中不能更新 UI 的操作,由此正是 Android 确实是不能在主线程中更新 UI 的,接下来我们来修改 MainActivity 中的代码如下:
/**
* Handler 测试
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView textView;
private Button button;
private static final int UPDATE_TEXT = 1;
private Handler handler = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
//在主线程中创建Handler,并从写 handleMessage 方法
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case UPDATE_TEXT :
//在这里可以进行UI操作
textView.setText("world");
break;
}
}
};
}
/**
* 响应点击事件
*
* @param v
*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
//点击按钮在子线程中更新 UI
new Thread(new Runnable() {
@Override
public void run() {
//创建 Message 对象
Message message = new Message();
message.what = UPDATE_TEXT;
//将 Message 对象发送出去
handler.sendMessage(message);
}
}).start();
break;
}
}
} 这里我们先是定义了一个整型常量 UPDATE_TEXT,用于表示更新 TextView 这个动作,然后新增一个 Handler 对象,并在 onCreate() 方法中把对象创建出来,并重写了父类的 handleMessage() 方法,在这里对具体的 Message 进行处理,如果发现 Message 的 what 值等于 UPDATE_TEXT,就将 TextView 的显示内容修改为 world,接下来在点击事件中,我们在子线程中并没有进行 UI 的更新,而是创建了 Message 对象,并将它的 what 字段值自定为 UPDATE_TEXT,然后调用 Handler 的sendMessage() 方法将这条 Message 发送出去,很快 Handler 就会收到这条消息,并在 handleMessage() 方法中对这条消息进行处理,需要注意的是,此时的 handleMessage() 方法就是运行在主线程当中的了,我们可以在这里进行 UI 操作三、Handler 原理是什么
Android 中异步消息处理机制主要由 4 部分组成:Message、Handler、MessageQueue 和 Looper,接下来我们就对这 4 个部分进行简单的介绍
1. Message
Message 是在线程之间传递消息,它可以在内部携带少量的信息,用于在不同线程之间交换数据,上面我们使用了 Message 的 what 字段,除此之外我们还可以使用 arg1 和 arg2 字段来携带一些整形数据,使用 obj 来携带一个 Object 对象
2. Handler
Handler 是消息的处理者,它主要用于发送和处理消息,发送消息一般是使用 Handler 的 sendMessage() 方法,而发出的消息经过一系列的处理后,最后会传到 Handler 的 handMessage() 方法中,我们来看 Handler 中的一个构造方法:
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;
}
这里通过 Looper.myLooper() 获取了当前线程保存的 Looper 实例,然后又获取了这个 Looper 实例中保存的 MessageQueue(消息队列),这样就保证了 Handler 的实例与我们 Looper 实例中 MessageQueue 关联上了,然后看我们最常用的 sendMessage() 方法
/**
* Pushes a message onto the end of the message queue after all pending messages
* before the current time. It will be received in {@link #handleMessage},
* in the thread attached to this handler.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
/**
* Sends a Message containing only the what value.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what, 0);
}
/**
* Sends a Message containing only the what value, to be delivered
* after the specified amount of time elapses.
* @see #sendMessageDelayed(android.os.Message, long)
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
/**
* Sends a Message containing only the what value, to be delivered
* at a specific time.
* @see #sendMessageAtTime(android.os.Message, long)
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageAtTime(msg, uptimeMillis);
}
/**
* Enqueue a message into the message queue after all pending messages
* before (current time + delayMillis). You will receive it in
* {@link #handleMessage}, in the thread attached to this handler.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the message will be processed -- if
* the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*/
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
/**
* Enqueue a message into the message queue after all pending messages
* before the absolute time (in milliseconds) <var>uptimeMillis</var>.
* <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
* Time spent in deep sleep will add an additional delay to execution.
* You will receive it in {@link #handleMessage}, in the thread attached
* to this handler.
*
* @param uptimeMillis The absolute time at which the message should be
* delivered, using the
* {@link android.os.SystemClock#uptimeMillis} time-base.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the message will be processed -- if
* the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*/
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);
}到最后调用了 sendMessageAtTime() 方法,在此方法内部有直接获取 MessageQueue 然后调用了 enqueueMessage() 方法,我们再来看看此方法:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}enqueueMessage() 中首先为 meg.target 赋值为 this,大家下面 Looper 的介绍中会看到 Looper 的 loop() 方法会取出每个 msg 然后交给 msg,target.dispatchMessage(msg) 去处理消息,也就是把当前的 handler 作为 msg 的 target 属性。最终会调用 queue 的 enqueueMessage() 的方法,也就是说 handler 发出的消息,最终会保存到消息队列中去。3. MessageQueue
MessageQueue 是消息队列,他主要用于存放所有通过 Handler 发送的消息,这部分消息一直存在于消息队列中,等待被处理,每一个线程中只会有一个 MessageQueue 对象
4. Looper
Looper 是每个线程中 MessageQueue 的管家,调用 Looper 的 loop() 方法后,就会进入到一个无限循环当中,然后每当发现 MessageQueue 中有消息,就会将它取出来,并传递到 Handler 的 handlerMessage() 方法中,每个线程中也只会有一个 Looper 对象
public static final void prepare() {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(true));
} 看 prepare() 方法,sThreadLocal 是一个 ThreadLocal 对象,可以在一个线程中存储变量。可以看到,在第 5 行,将一个 Looper 的实例放入了 ThreadLocal,并且判断了 sThreadLocal 是否为 null,否则抛出异常。这也就说明了 Looper.prepare() 方法不能被调用两次,同时也保证了一个线程中只有一个 Looper 实例,接下来我们来看一下 Looper 是来如何构造的:private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mRun = true;
mThread = Thread.currentThread();
} 在构造方法中,创建了一个我们上面提到的 MessageQueue(消息队列)。再看 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;
// 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();
}
}这里直接返回了 myLooper() 对象: /**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
} 方法直接返回了 sThreadLocal 存储的 Looper 实例,如果 me 为 null 则抛出异常,也就是说 looper() 方法必须在 prepare() 方法之后运行,接下来拿到该 looper 实例中的 mQueue(消息队列),再往下的 for 循环就进入了我们所说的无限循环。接下来取出一条消息,如果没有消息则阻塞,并且调用 msg.target.dispatchMessage(msg),把消息交给 msg 的 target 的 dispatchMessage 方法去处理。Msg 的 target 是什么呢?其实就是 handler 对象。最后通过 msg.recycleUncheked() 释放消息占据的资源。四、如何定义一个与线程相关的 Handler
1. 我们分别定义一个主线程的 Handler 和一个子线程的 Handler,修改 MainActivity 中的代码如下:
/**
* Handler 测试
*/
public class MainActivity extends AppCompatActivity {
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.e("UI-------->", Thread.currentThread().toString());
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//创建子线程对象,并开启
MyThread myThread = new MyThread();
myThread.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
myThread.handler1.sendEmptyMessage(1);
handler.sendEmptyMessage(1);
}
/**
* 创建子线程
*/
class MyThread extends Thread {
public Handler handler1;
@Override
public void run() {
Looper.prepare();
handler1 = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.e("所在线程-------->", Thread.currentThread().toString());
}
};
Looper.loop();
}
}
}打印结果如下:
这里其实没有什么,主要是告诉大家如何分别在主线程和子线程中创建 Handler,需要注意的是在子线程中创建需要自己调用 Looper.prepare() 方法和 Lopper.loop() 方法,从打印的情况我们也可以看出我们创建的 Handler 分别运行在各自的线程中
五、Android 更新 UI 的几种方式
第一种就是我们文章中一开始使用的方式
第二种是通过 handler.post 方法,代码如下:
/**
* Handler 测试
*/
public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
//在子线程中更新 UI
new Thread() {
@Override
public void run() {
firstHandler();
}
}.start();
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
/**
* 第二种更新方法,通过 handler.post
*/
private void firstHandler() {
handler.post(new Runnable() {
@Override
public void run() {
textView.setText("handler");
}
});
}
}3. 通过 runOnUiThread 方法,代码如下:/**
* Handler 测试
*/
public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
//在子线程中更新 UI
new Thread() {
@Override
public void run() {
updataUI();
}
}.start();
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
/**
* 第二种更新方法,通过 handler.post
*/
private void firstHandler() {
handler.post(new Runnable() {
@Override
public void run() {
textView.setText("handler");
}
});
}
/**
* 通过 runOnUiThread 方法
*/
private void updataUI() {
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText("handler");
}
});
}
}4. 通过 veiw.post 更新/**
* Handler 测试
*/
public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
//在子线程中更新 UI
new Thread() {
@Override
public void run() {
viewUI();
}
}.start();
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
/**
* 第二种更新方法,通过 handler.post
*/
private void firstHandler() {
handler.post(new Runnable() {
@Override
public void run() {
textView.setText("handler");
}
});
}
/**
* 第三种更新方法,通过 runOnUiThread 方法
*/
private void updataUI() {
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText("handler");
}
});
}
/**
* 第四种更新方法,通过 view.post 方法
*/
private void viewUI() {
textView.post(new Runnable() {
@Override
public void run() {
textView.setText("handler");
}
});
}
}上面我们就介绍完了所有跟新 UI 的方法,大家可以自行根据情况选择适当的方法在不同的场景下六、非 UI 线程真的不能更新 UI 吗
/**
* Handler 测试
*/
public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
//在子线程中更新 UI
new Thread(new Runnable() {
@Override
public void run() {
try {
//关键在这里
//如果加上这一句话,程序运行崩溃
//如果不加这一句话,居然就会在子线程里面更新UI
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
textView.setText("子线程中访问");
}
}).start();
}
}如果代码崩溃,程序会抛出如下异常,就像我们上面看到的一样android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.Java:6581)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:924)
那么为什么一个不休眠 2 秒的就不会抛出异常,这是因为,ViewRootImpl 的 checkThread() 方法,会检查更新 UI 的线程如下
void checkThread() {
if (mThread != Thread.currentThread()) {
throw new CalledFromWrongThreadException(
"Only the original thread that created a view hierarchy can touch its views.");
}
} 经过研究源码发现,ViewRootImpl 是在 onResume() 方法回调之后创建的。所以,对于没有崩溃的原因就是,子线程在onCreate() 中更新 UI 的时候,ViewRootImpl 还没有创建。反过来,崩溃的原因就是子线程在 Thread.sleep(2000) 后,ViewRootImpl 已经创建了,并且通过 checkThread() 抛出的异常。
针对 checkThread() 方法中抛出的异常信息,相信大家在开发过程中也遇到过,由于这一点的限制导致必须在主线程中访问UI,但是 Android 又不建议在主线程中进行耗时的操作,否则会导致程序无法响应,即我们经常所说的 ANR 异常,这里我们想一下,为什么在子线程中不能更新 UI 呢?这是因为,Android 的 UI 控件不是线程安全的,如果在多线程中并发访问,可能会导致 UI控件处于不可预期状态,那么系统为什么不对 UI 控件的访问加上锁机制,这是因为,锁机制会降低 UI 访问的效率,因为锁机制会阻塞某些线程的执行,最简单的高效的方法是采用单线程模型来处理 UI 操作,对于开发者来说也不是很麻烦,只需要通过 Handler切换一下 UI 访问的执行线程即可。
七、Handler 使用过程中遇到的问题
以上其实就是我们在使用 Handler 过程中会遇到的一些问题总结
最后总结:从开发的角度来讲,Handler 是 Android 消息机制的上层接口,但从本质上来说,Handler 并不是专门用来更新 UI 的,它只是常被开发者用来更新 UI
441



被折叠的 条评论
为什么被折叠?



