android Handler发送与处理消息小结

1.Looper处理消息的逻辑:

分发消息

for (;;) {
Message msg = queue.next(); // might block
//这里的target指的就是handler
msg.target.dispatchMessage(msg);

msg.recycle();
}
处理消息

public void dispatchMessage(Message msg) {
if (msg.callback != null) {
//如果message上外接有消息处理回调对象,就调用message上外接的消息处理回调对象
handleCallback(msg);
} else {
//如果handler上外接有消息处理回调对象,就调用handler上外接的消息处理回调对象
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
//这里会返回一个bool值,为true表示调用完mCallback之后,不会调用重写的handleMessage方法,为false表示会继续调用重写的handleMessage方法
return;
}
}
//最后一种情况就是调用重写的handleMessage方法
handleMessage(msg);
}
}
优先级msg.callback >mCallback > handleMessage

2.Hnadler发送消息的几种方式

(1)Handler.SendEmptyMessage(what);
(2)Handler.obtainMessage(int what, int arg1, int arg2, Object obj).sendYToTarget();
(3)Message.obtain(handler, MESSAGE_MSG, 0, 0, msg).sendToTarget();
(4)Message message = Message.obtain();
    message.what = PROGRESS_MSG;
    message.arg1 = progress;
    handler.sendMessage(message);
(5)handler.post(Runnable callback)

3. 下面就做一个demo:handler接收消息使用handler外接的callback回调,发送消息则分别使用了上面的:(2)handler.obtainMessage,(3)Message.obtain,(4)三种方法。

handler发送消息的三种方法:

public void postError(String errMsg)
{
handler.obtainMessage(MESSAGE_ERR, errMsg).sendToTarget();
}


public void postMessage(String msg)
{
Message.obtain(handler, MESSAGE_MSG, 0, 0, msg).sendToTarget();
}


public void postProgress(long i, long size)
{
int progress = (int) (i * 100 / size);
Message message = Message.obtain();
message.what = PROGRESS_MSG;
message.arg1 = progress;
handler.sendMessage(message);
}

handler接收消息使用handler外接的回调:

handler = new Handler(new MsgCallBack());
class MsgCallBack implements Callback
{


@Override
public boolean handleMessage(Message msg)
{
switch (msg.what) {
case PROGRESS_MSG:
                int progress= msg.arg1;
                processDialog.setProgress(progress);
                if(progress==100)
                {
                processDialog.dismiss();
                }
break;
case MESSAGE_MSG:
                Toast.makeText(MainActivity.this, (String)msg.obj, Toast.LENGTH_LONG).show();
break;
case MESSAGE_ERR:
                new AlertDialog.Builder(MainActivity.this)
                .setTitle("下载错误")
                .setMessage((String)msg.obj)
                .show();
                processDialog.dismiss();
break;


default:
break;
}
return true;
}
}

有兴趣的同学可以去看下demo:

点击打开链接

你可能感兴趣的:(android Handler发送与处理消息小结)