Handler用sendEmptyMessage(int what)发消息,其实也可以用sendMessage(Message msg)的,但两者到底有啥区别?
直接上Handler源码:
/**
* 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);
}
就是调用了sendEmptyMessageDelayed()而已,下面看下这个方法:
/**
* 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);
}
而sendMessage(Message msg)的实现和上面一样,请看:
/**
* 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);
}
就是在
sendEmptyMessageDelayed中就是构建了一个Message,然后把这个Message的what设置成sendEmptyMessage方法中的What参数即可。
比如:
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
ll_pb.setVisibility(View.INVISIBLE);
if(adapter == null){
adapter = new CallSafeAdapter(blackNumberInfos, CallSafeActivity.this);
list_view.setAdapter(adapter);
}else{
adapter.notifyDataSetChanged();
}
}
};
private void initData() {
dao = new BlackNumberDao(CallSafeActivity.this);
//一共有多少条数据
totalNumber = dao.getTotalNumber();
new Thread() {
@Override
public void run() {
//分批加载数据
if (blackNumberInfos == null) {
blackNumberInfos = dao.findPar2(mStartIndex, maxCount);
} else {
//把后面的数据。追加到blackNumberInfos集合里面。防止黑名单被覆盖
blackNumberInfos.addAll(dao.findPar2(mStartIndex, maxCount));
}
handler.sendEmptyMessage(0);
}
}.start();
}
当在子线程里的耗时操作已经结束了,这是我们需要发送一个消息告诉主线程我的耗时操作已经结束了,你赶紧处理吧!