Android Handler机制

面试题:解释一下Android中Handler,Message,Looper之间的关系?
android提供了Handler和Looper来满足线程间的通信。Handler是先进先出原则。Looper类用来管理特定线程内对象之间的消息交换(Message Exchange).
1 Looper:一个线程可以产生一个Looper对象,由它来管理此线程的Message Queue(消息队列).
2 Handler:可以构造Handler对象来与Looper沟通,以便push新消息到Message Queue里;或者接受Looper从Message Queue取出所送来的消息.
3 Message Queue(消息队列):用来存放线程放入的消息.
**4 线程:**UI thread 通常就是main thread,而Android启动程序时就会替他建立一个Message Queue.

常用的三种UI更新的方法:

(1)Handler.post()方式;

该方法使用Handler中的post()方法更新UI,这里会涉及Thread,Runnable两个线程的概念,先暂且忽略吧。该方法比较简单,容易理解。先贴上代码:

public class MainActivity extends Activity {

private TextView text;
private Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (TextView) findViewById(R.id.id_text);

    /**
     * new Thread()在该线程中实现你具体的业务逻辑,比如网络请求,耗时操作等等;
     * new Thread()是一个子线程,是非UI线程,如果在该线程中需要更新界面,则需要使用Handler;
     *
     */
    new Thread() {
        @Override
        public void run() {
            //在run()方法实现业务逻辑;
            //...

            //更新UI操作;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    text.setText(使用Handler更新了界面);
                }
            }); 
        }
    }.start();
}
}

注意看其中的注释。开发者的对线程的业务逻辑操作写在Thread.run()方法中,更新UI的操作写到Runnable.run()方法中。

(2)Handler.post()方式;

该方法与方法1非常像,只是新建了一个内部类,并且实现了Runnable接口,然后在post()方法中不用new一个匿名内部类了。相对来说逻辑上更加清楚。思路同方法1.贴上代码如下:

public class MainActivity extends Activity {

private TextView text;
private Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (TextView) findViewById(R.id.id_text);
    final MyRunnable myRunnable = new MyRunnable();//定义MyRunnable的对象;

    new Thread() {

        @Override
        public void run() {
            handler.post(myRunnable);//调用Handler.post方法;
        }
    }.start();
}

class MyRunnable implements Runnable {//内部类实现Runnable接口;

    @Override
    public void run() {//还是在Runnable重写的run()方法中更新界面;
        text.setText(使用Handler更新了界面);
    }
}
}

注意提醒一点:Thread必须调用start()方法,否则线程不会被执行。

(3)sendMessage(),handleMessage()方式;

在Handler中有两个非常重要的方法,sendMessage()和handleMessage()方法,sendMessage()方法用于在线程中向Handler发送一个消息,handleMessage()用于捕获该消息,并且更新UI.代码如下:

public class MainActivity extends Activity {

private TextView text;
private Handler handler = new Handler() {

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case 1:
                text.setText(使用Handler更新了界面);
                break;
        }
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (TextView) findViewById(R.id.id_text);

    new Thread() {

        @Override
        public void run() {
            //...你的业务逻辑;
            //发送一个消息,该消息用于在handleMessage中区分是谁发过来的消息;
            Message message = Message.obtian();              
            message.what = 1;
            handler.sendMessage(message);
        }
    }.start();
}
}

源码解析:

1、Looper
对于Looper主要是prepare()和loop()两个方法。
首先看prepare()方法

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));  
 } 

sThreadLocal是一个ThreadLocal对象,可以在一个线程中存储变量。可以看到,在第5行,将一个Looper的实例放入了ThreadLocal,并且2-4行判断了sThreadLocal是否为null,否则抛出异常。这也就说明了Looper.prepare()方法不能被调用两次,同时也保证了一个线程中只有一个Looper实例。

下面看Looper的构造方法:

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

在构造方法中,创建了一个MessageQueue(消息队列)。
然后我们看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.recycle();  
    }  
    }  

第2行:
public static Looper myLooper() {
return sThreadLocal.get();
}
方法直接返回了sThreadLocal存储的Looper实例,如果me为null则抛出异常,也就是说looper方法必须在prepare方法之后运行。
第6行:拿到该looper实例中的mQueue(消息队列)
13到45行:就进入了我们所说的无限循环。
14行:取出一条消息,如果没有消息则阻塞。
27行:使用调用 msg.target.dispatchMessage(msg);把消息交给msg的target的dispatchMessage方法去处理。Msg的target是什么呢?其实就是handler对象,下面会进行分析。
44行:释放消息占据的资源。

Looper主要作用:
1、 与当前线程绑定,保证一个线程只会有一个Looper实例,同时一个Looper实例也只有一个MessageQueue。
2、 loop()方法,不断从MessageQueue中去取消息,交给消息的target属性的dispatchMessage去处理。
好了,我们的异步消息处理线程已经有了消息队列(MessageQueue),也有了在无限循环体中取出消息的哥们,现在缺的就是发送消息的对象了,于是乎:Handler登场了。

2、Handler
使用Handler之前,我们都是初始化一个实例,比如用于更新UI线程,我们会在声明的时候直接初始化,或者在onCreate中初始化Handler实例。所以我们首先看Handler的构造方法,看其如何与MessageQueue联系上的,它在子线程中发送的消息(一般发送消息都在非UI线程)怎么发送到MessageQueue中的。

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;  
}  

14行:通过Looper.myLooper()获取了当前线程保存的Looper实例,然后在19行又获取了这个Looper实例中保存的MessageQueue(消息队列),这样就保证了handler的实例与我们Looper实例中MessageQueue关联上了。
然后看我们最常用的sendMessage方法

public final boolean sendMessage(Message msg)  
 {  
 return sendMessageDelayed(msg, 0);  
 }


public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {  
 Message msg = Message.obtain();  
 msg.what = what;  
 return sendMessageDelayed(msg, delayMillis);  
}  


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的loop方法会取出每个msg然后交给msg,target.dispatchMessage(msg)去处理消息】,也就是把当前的handler作为msg的target属性。最终会调用queue的enqueueMessage的方法,也就是说handler发出的消息,最终会保存到消息队列中去。

现在已经很清楚了Looper会调用prepare()和loop()方法,在当前执行的线程中保存一个Looper实例,这个实例会保存一个MessageQueue对象,然后当前线程进入一个无限循环中去,不断从MessageQueue中读取Handler发来的消息。然后再回调创建这个消息的handler中的dispathMessage方法,下面我们赶快去看一看这个方法:

 public void dispatchMessage(Message msg) {  
    if (msg.callback != null) {  
        handleCallback(msg);  
    } else {  
        if (mCallback != null) {  
            if (mCallback.handleMessage(msg)) {  
                return;  
            }  
        }  
        handleMessage(msg);  
    }  
}  

可以看到,第10行,调用了handleMessage方法,下面我们去看这个方法:

/** 
     * Subclasses must implement this to receive messages. 
     */  

  public void handleMessage(Message msg) {  
  }  

可以看到这是一个空方法,为什么呢,因为消息的最终回调是由我们控制的,我们在创建handler的时候都是复写handleMessage方法,然后根据msg.what进行消息处理。
例如:

 private Handler mHandler = new Handler()  
{  
    public void handleMessage(android.os.Message msg)  
    {  
        switch (msg.what)  
        {  
        case value:  

            break;  

        default:  
            break;  
        }  
    };  
}; 

到此,这个流程已经解释完毕,让我们首先总结一下
1、首先Looper.prepare()在本线程中保存一个Looper实例,然后该实例中保存一个MessageQueue对象;因为Looper.prepare()在一个线程中只能调用一次,所以MessageQueue在一个线程中只会存在一个。
2、Looper.loop()会让当前线程进入一个无限循环,不端从MessageQueue的实例中读取消息,然后回调msg.target.dispatchMessage(msg)方法。
3、Handler的构造方法,会首先得到当前线程中保存的Looper实例,进而与Looper实例中的MessageQueue想关联。
4、Handler的sendMessage方法,会给msg的target赋值为handler自身,然后加入MessageQueue中。
5、在构造Handler实例时,我们会重写handleMessage方法,也就是msg.target.dispatchMessage(msg)最终调用的方法。
好了,总结完成,大家可能还会问,那么在Activity中,我们并没有显示的调用Looper.prepare()和Looper.loop()方法,为啥Handler可以成功创建呢,这是因为在Activity的启动代码中,已经在当前UI线程调用了Looper.prepare()和Looper.loop()方法。

Android不仅给我们提供了异步消息处理机制让我们更好的完成UI的更新,其实也为我们提供了异步消息处理机制代码的参考。。。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值