Looper原理及自定义消息处理线程

原因:
为什么要自定义消息处理机制?使用AsyncTask子类实现消息处理,很方面,但是可控性差,无法进行自定义的其他譬如 暂停功能

Android系统自带Looper机制分析:
下图是Handler在UI主线程中的使用图,其他子线程使用handler发送消息到MQ中,Looper对象.looper()之后就是循环去查询MQ,
如果有消息,就去调用handler的.handlerMessager()方法处理这个消息。

ss

3.下面使用系统提供的几个类自定义一个消息处理线程:
自定义一个消息处理线程,处理所有其他线程发送过来的消息,模拟系统UI线程这个流程:
1.一个自定义的线程mThread
2.消息队列容器MessageQueue
3.Looper消息轮询器,从MQ中按顺序取出消息,交给Main线程进行处理
4.接收消息,并将消息放到MQ中,这是Handler
5.消息对象,消息的容器Message

首先创建MQ和Looper对象,从系统Looper的的提示上看到,在一个Thread的run方法中,Looper.prepear()会初始化当前的thread对象为一个Looper,
然后让handler对象引用该looper。并且之后一定要调用Looper.loop()方法。

Initialize the current thread as a looper. This gives you a chance to create handlers that then reference this looper, before actually starting the loop. Be sure to call loop() after calling this method, and end it by calling quit().

   
   
private Handler mHandler;//set/get  
private void createMQ() {
new Thread("自定义"){
public void run() {
Looper.prepare();
mHandler = new Handler() {//把mHander作为外层类的Field,供其他发送消息的对象引用。
public void handleMessage(Message msg) {
Log.i(Thread.currentThread().getName(), (String)msg.obj);
}
};
Looper.loop();

}
}.start();
}

决定Handler处理哪个线程的消息队列MQ,是由new Handler构造函数决定的。Looper对象来自哪个线程,而不是Handler的创建位置。

Handler()无参构造的注释是:

Default constructor associates this handler with the queue for the current thread. If there isn't one, this handler won't be able to receive messages. 

默认的构造函数关联了一个来自当前线程的队列(queue)。就是说,默认使用的主线程的MQ,也可显示引用:

new Handler(Looper.getMainLooper());

Looper的静态方法返回Main函数的Looper.


如果要使用自定义的一个消息队列,需要自己new,或者使用Looper.prepare()代码执行之后自动创建的一个MQ,它从属于该线程,使用Looper.getMyLooper():

new Handler(Looper.myLooper());//Use the provided queue instead of the default one.

使用looper对象的构造方法,使用提供的queue代替默认的主线程的MQ,参数是looper为什么说成是queue呢?因为queue从属于一个Looper对象,可以使用

Looper.myLooper().myQueue();获取到MQ对象。


测试:将Looper对象拿到,然后变成外层对象的变量,在外层对象创建一个Handler对象,将该Looper实例传给Handler构造函数,

启动测试,发现Handler所处理的线程在自定义线程中,这是因为Looper对象来自于自定义线程;而如果将Handler调用为无参函数,

那么显示来自于main函数。


这样使用自定义的线程对象就可以随时进行控制,暂停cancel之类的操作了。




 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值