Handler机制总结

handler的主要作用是将一个任务切换到指定的线程中去执行 ,最常用的就是在子线程中通过handler将任务切换到UI线程去更新UI。

主要用法:
我们知道Android不允许在子线程中更新UI的,这是因为UI线程不是线程安全的,为什么这么说呢,如果在多线程并发访问UI,那么UI可能不处于不可预期的状态,Android是没有给UI控件访问加锁机制的,若果这样做首先UI的访问逻辑无疑会变得复杂,其次会降低Ui的访问效率,加了锁可能就会阻塞某些线程的执行。
一般的我们在子线程进行了某个耗时操作,然后会需要在UI线程中去改变UI的状态,这是一个非常常见的需求。就可以这样做

public class MainActivity extends AppCompatActivity {
private TextView mTextView;
Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
if (msg.what == 0){
mTextView.setText("update");
}
        }
    };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView)findViewById(R.id.textView);
        new Thread(){
@Override
public void run() {
try {
                    Thread.sleep(2000);
mHandler.sendEmptyMessage(0);
} catch (InterruptedException e) {

                }
            }
        }.start();
}
}

除了发送一个msg之外,handler还可以发送一个Runnable对象,跟上边发送一个msg实现的功能一样

Handler mHandler = new Handler();
new Thread(){
@Override
public void run() {
try {
            Thread.sleep(2000);
mHandler.post(new Runnable() {
@Override
public void run() {
mTextView.setText("update");
}
            });
} catch (InterruptedException e) {

        }
    }
}.start();

也可以通过sendMessage(msg)方法发送一个Message对象,Message对象可以携带参数,也可以携带一个Object

Message message = new Message();
message.what = 0;
message.arg1 = 1000;
mHandler.sendMessage(message);
public void handleMessage(Message msg) {
if (msg.what == 0){
mTextView.setText(msg.arg1+"");
}
}

除了使用new Massage()的方式创建一个Message之外,还可以通过
Message message = mHandler.obtainMessage();获取一个系统的message。也可以使用message.sendToTarget();去发送给handler。看源码:

public void sendToTarget() {
target.sendMessage(this);
}

target是什么呢,打开obtainMessage(),看到target就是刚才获取Message的mHandler自己。

public final Message obtainMessage()
{
return Message.obtain(this);
}
public static Message obtain(Handler h) {
    Message m = obtain();
m.target = h;

    return m;
}

还有一种新建handler的方式通过这种传入Callback的方式,在返回值为true或者false时分别截获和不截获消息。

Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
        Toast.makeText(getApplicationContext(),"1",1).show();
        return false;
}
}){
@Override
public void handleMessage(Message msg) {
        Toast.makeText(getApplicationContext(), "2", 1).show();
}
};

**

handler,message,messageQueue,Looper之间的关系

**
handle的机制主要靠MessageQueue和Looper来实现,每当handler发送一个消息msg或者post一个Runnable对象(会被包装成message),msg会通过MessageQueue的enqueueMessage()方法加入到消息队列,然后Looper通过无限循环的方式查找消息队列是否有新消息,有的话就处理,最终消息中的Runnable或者handleMessage方法会被调用。Looper是与创建Handler的线程绑定的,主线程中默认创建了Looper,但是子线程不会自己创建,若要在子线程中创建handler,需要自己创建一个Looper,方法是Looper.prepare()创建成功后调用Looper.loop开启循环。如下,从一个子线程将任务切换到另外一个子线程。

new Thread("Thread1"){
@Override
public void run() {
        Looper.prepare();
handler = new Handler();
Looper.loop();
}
}.start();
new Thread("Thread2"){
@Override
public void run() {
try {
            Thread.sleep(2000);
handler.post(new Runnable() {
@Override
public void run() {
                    Log.e("fwc",Thread.currentThread().getName());
}
            });
} catch (InterruptedException e) {
            e.printStackTrace();
}
    }
}.start();

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("MessageQueue", 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) {
            // New head, wake up the event queue if blocked.
            msg.next = p;
            mMessages = msg;
            needWake = mBlocked;
        } else {
            // Inserted within the middle of the queue.  Usually we don't have to wake
            // up the event queue unless there is a barrier at the head of the queue
            // and the message is the earliest asynchronous message in the queue.
            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; // invariant: p == prev.next
            prev.next = msg;
        }

        // We can assume mPtr != 0 because mQuitting is false.
        if (needWake) {
            nativeWake(mPtr);
        }
    }
    return true;
}

另外一个是next方法,next方法是一个无限循环的方法,当消息队列中没有消息的时候会一直阻塞在这里,当有新消息到来时,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 (false) Log.v("MessageQueue", "Returning message: " + msg);
                    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("MessageQueue", "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;
    }
}

Looper工作机制

private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

通过构造方法可以看到Looper内部有MessageQueue,并且与当前线程绑定。looper的主要方法是loop();无限循环去调用messageQueue的next方法,当返回值为null的时候跳出循环,否则,msg.target.dispatchMessage(msg);之前说了这个target就是Handler本身,继续跟源码看到,如果msg.callback != null(这个callback是一个Runnable的,就是之前post一个Runnable对象的callback)就执行callback的run方法。否则执行自己的callback的handleMessage方法,就是之前说的返回值为true的时候截获消息,最后才是handler的handleMessage方法。这样就从一个线程切换到了handler所在的线程。Looper可以调用quit方法停止,会调用messageQueue的quit方法,将消息队列标记为退出。标记之后next方法会返回null;

/**
 * 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
        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();
    }
}
public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}

handler工作原理
sendMessage方法最终只是调用了enqueueMessage方法将消息插入到了MessageQueue中,Looper的loop方法循环调用messageQueue的next方法从消息队列中取出消息,调用handler的dispatchMessage方法,之后就与上边分析的一致了。
前边说了子线程中创建handler需要自己调用Looper的prepare方法创建一个与当前线程绑定的Looper,并调用loop方法才能让整个handler运转起来,那么主线程的Looper是什么时候创建的呢,Android的主线程是ActivityThread,入口是main方法,看到在main方法中调用了Looper.prepareMainLooper();创建了一个主线程的Looper并且开启了循环。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值