zoukankan      html  css  js  c++  java
  • (转)深入理解之 Android Handler(相当好!!!)

     一,相关概念

    在Android中如果通过用户界面(如button)来来启动线程,然后再线程中的执行代码将状态信息输出到用户界面(如文本框),这时候就会抛出以下的异常信息:

    5-12 13:33:04.393: ERROR/JavaBinder(1029):android.view.ViewRoot$CalledFromWrongThreadException:Onlythe original thread that created a view hierarchy can touch its views.

    该异常的意思是,只有最初创建视图层次结构的线程才能接触该结构中的视图,也就是说,不是最初创建界面的线程是不能接触界面元素的。那么,在不是创建界面的线程中,如何把内容输出到界面元素中呢?

    对了,我们可以通过线程消息分发机制来实现。就应用程序而言,Android系统中Java的应用程序和其他系统上一样,都是依赖于消息驱动完成那些比较有难度的工作,它们的工作原理大致是分别有一个消息队列负责接收各种消息,一个消息循环可以不断从中取出消息然后做处理。先了解一下几个消息机制的常见名词概念:

    • Handler

    消息的封装者和处理者,handler负责将需要传递的信息封装成Message,通过调用handler对象的obtainMessage()来实现;将消息传递给Looper,这是通过handler对象的sendMessage()来实现的。继而由Looper将Message放入MessageQueue中。当Looper对象看到MessageQueue中含有Message,就将其广播出去。该handler对象收到该消息后,调用相应的handler对象的handleMessage()方法对其进行处理。

    • Message

    消息对象,Message Queue中的存放的对象。一个Message Queue中包含多个Message。Message实例对象的取得,通常使用Message类里的静态方法obtain(),该方法有多个重载版本可供选择;它的创建并不一定是直接创建一个新的实例,而是先从Message Pool(消息池)中看有没有可用的Message实例,存在则直接取出返回这个实例。如果Message Pool中没有可用的Message实例,则才用给定的参数创建一个Message对象。调用removeMessages()时,将Message从Message Queue中删除,同时放入到Message Pool中。除了上面这种方式,也可以通过Handler对象的obtainMessage()获取一个Message实例。

    • MessageQueue

    是一种数据结构,见名知义,就是一个消息队列,存放消息的地方。每一个线程最多只可以拥有一个MessageQueue数据结构。创建一个线程的时候,并不会自动创建其MessageQueue。通常使用一个Looper对象对该线程的MessageQueue进行管理。主线程创建时,会创建一个默认的Looper对象,而Looper对象的创建,将自动创建一个Message Queue。其他非主线程,不会自动创建Looper,要需要的时候,通过调用prepare函数来实现。

    • Looper

    是MessageQueue的管理者。每一个MessageQueue都不能脱离Looper而存在,Looper对象的创建是通过prepare函数来实现的。同时每一个Looper对象和一个线程关联。通过调用Looper.myLooper()可以获得当前线程的Looper对象创建一个Looper对象时,会同时创建一个MessageQueue对象。除了主线程有默认的Looper,其他线程默认是没有MessageQueue对象的,所以,不能接受Message。如需要接受,自己定义一个Looper对象(通过prepare函数),这样该线程就有了自己的Looper对象和MessageQueue数据结构了。Looper从MessageQueue中取出Message然后,交由Handler的handleMessage进行处理。处理完成后,调用Message.recycle()将其放入Message Pool中。

    二,Looper类分析

    当需要向其他线程发消息时我们需要实例化Looper对象会有以下两步:

    1,Looper.prepare()

    我们可以看下源码:

    1 // sThreadLocal.get() will return null unless you've called prepare().  
    2     static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();   
    3 public static void prepare() {   
    4        if (sThreadLocal.get() != null) {   
    5            throw new RuntimeException("Only one Looper may be created per thread");   
    6        }   
    7  // 构造一个Looper对象,保存到调用线程的局部变量中。  
    8         sThreadLocal.set(new Looper());   
    9    }

    可以看出来,Looper.prepare()会在调用线程的局部变量中设置一个Looper对象。这个调用线程就是LooperThread的run线程。F3看一下Looper的构造方法:

    1 private Looper() {  
    2      //构造一个消息队列  
    3         mQueue = new MessageQueue();  
    4         mRun = true;  
    5      //获取当前线程的Thread对象  
    6         mThread = Thread.currentThread();  
    7     }  

    所以Looper.prepare()的作用是设置一个Looper对象保存在sThreadLocal里,而Looper自己内部封装了一个消息队列。就这样把Looper和调用线程关联在一起了。到底要干嘛,我们看Looper的第二步棋

    2,Looper.loop()

     1 public static void loop() {  
     2         //myLooper()将会返回保存在sThreadLocal中的Looper对象。  
     3         Looper me = myLooper();  
     4         if (me == null) {  
     5             throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");  
     6         }  
     7         //取出该Looper中的消息队列  
     8         MessageQueue queue = me.mQueue;    
     9         while (true) {  
    10             //处理消息,Message对象中有一个target,它是Handle类型  
    11             Message msg = queue.next(); // might block  
    12             if (msg != null) {  
    13                 if (msg.target == null) {  
    14                     // No target is a magic identifier for the quit message.  
    15                     return;  
    16                 }  
    17                 msg.target.dispatchMessage(msg);  
    18                 msg.recycle();  
    19             }  
    20         }  
    21     }  
    22   
    23     /** 
    24      * Return the Looper object associated with the current thread.  Returns 
    25      * null if the calling thread is not associated with a Looper. 
    26      */  
    27     public static Looper myLooper() {  
    28         return sThreadLocal.get();  
    29     }  

    综上可以知道Looper类的作用是:

    封装了一个消息队列;

    Looper的prepare方法把这个Looper和调用prepare的线程绑定在一起;

    处理线程调用loop方法,处理来自该消息队列的消息。

    三,Handler类分析

    1,好多构造函数

    一样看去,我们可以看到几个眼熟的家伙:MessageQueue,Looper,Callback,一个不少,他们是干嘛的?往下看发现有4个形态不一的构造函数:

     1 /** 
     2      * 构造函数一,铁板一块,不过也完成了调用线程的Looper,并获得它的消息队列。 
     3      */  
     4     public Handler() {  
     5         mLooper = Looper.myLooper();  
     6         if (mLooper == null) {  
     7             throw new RuntimeException(  
     8                 "Can't create handler inside thread that has not called Looper.prepare()");  
     9         }  
    10         mQueue = mLooper.mQueue;  
    11         mCallback = null;  
    12     }  
    13   
    14     /** 
    15      * 构造函数二,多了一个callback 
    16      */  
    17     public Handler(Callback callback) {  
    18         mLooper = Looper.myLooper();  
    19         if (mLooper == null) {  
    20             throw new RuntimeException(  
    21                 "Can't create handler inside thread that has not called Looper.prepare()");  
    22         }  
    23         mQueue = mLooper.mQueue;  
    24         mCallback = callback;  
    25     }  
    26   
    27     /** 
    28      * 构造函数三,Looper由外部传入,定制。 
    29      */  
    30     public Handler(Looper looper) {  
    31         mLooper = looper;  
    32         mQueue = looper.mQueue;  
    33         mCallback = null;  
    34     }  
    35   
    36     /** 
    37      * 构造函数四,它是2和3的结合体。 
    38      */  
    39     public Handler(Looper looper, Callback callback) {  
    40         mLooper = looper;  
    41         mQueue = looper.mQueue;  
    42         mCallback = callback;  
    43     }  

    在上面的构造函数中,Handler中的消息队列变量最终都会指向Looper的消息队列,Handler为啥要这么做,我们继续挖。

    2,Handler的真正使命

    通过分析Handler源代码,可以发现它的作用就是提供一系列函数,方便我们完成消息的创建封装和插入到消息队列:

     1 //查看消息队列中是否有存货  
     2   public final boolean hasMessages(int what) {  
     3         return mQueue.removeMessages(this, what, null, false);  
     4     }  
     5 //创建封装一个消息  
     6   public final Message obtainMessage(int what)  
     7     {  
     8         return Message.obtain(this, what);  
     9     }  
    10 //发送一个消息,并添加到队列尾  
    11   public final boolean sendMessage(Message msg)  
    12     {  
    13         return sendMessageDelayed(msg, 0);  
    14     }  
    15 //延时发送一个消息,并添加到队列尾  
    16   public final boolean sendMessageDelayed(Message msg, long delayMillis)  
    17     {  
    18         if (delayMillis < 0) {  
    19             delayMillis = 0;  
    20         }  
    21         return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);  
    22     }  

    选其一进行分析,就sendMessageDelayed()了,F3进去:

     1 public boolean sendMessageAtTime(Message msg, long uptimeMillis)  
     2     {  
     3         boolean sent = false;  
     4         MessageQueue queue = mQueue;  
     5         if (queue != null) {  
     6 //把Message的target设置为自己,然后加入消息队列中  
     7             msg.target = this;  
     8             sent = queue.enqueueMessage(msg, uptimeMillis);  
     9         }  
    10         else {  
    11             RuntimeException e = new RuntimeException(  
    12                 this + " sendMessageAtTime() called with no mQueue");  
    13             Log.w("Looper", e.getMessage(), e);  
    14         }  
    15         return sent;  
    16     }  

    以上工作是往Looper的消息队列中加入了一个消息,按照Looper类分析可知,它在获取消息后会调用target的dispatchMessage函数,再把这个消息分发给Handle处理,接着继续看Handler.java:

     1 public void dispatchMessage(Message msg) {  
     2 // 1,如果Message本身有callback,则直接交给Message的callback处理  
     3         if (msg.callback != null) {  
     4             handleCallback(msg);  
     5         } else {  
     6 // 2,如果本Handle设置了mCallback,则交给它处理  
     7             if (mCallback != null) {  
     8                 if (mCallback.handleMessage(msg)) {  
     9                     return;  
    10                 }  
    11             }  
    12 // 3,啥也没有,就交给子类来处理  
    13             handleMessage(msg);  
    14         }  
    15     }  

    在绝大多数情况下,我们都是走的第三部流程,用一个从Handler派生的子类并重载handleMessage()来处理各种封装的消息。

    小结:1,Looper中有一个Message队列,里面储存的是一个个待处理的Message。

                 2,Message中有一个Handler,这个Handler是用来处理Message的。

    四,实战篇

    1,主线程给自己发消息

     1 public class handler1 extends Activity {  
     2         private Button btnTest;  
     3         private EditText textView;  
     4         private final String tag="hyj_handler1";  
     5         private Handler handler;  
     6     /** Called when the activity is first created. */  
     7     @Override  
     8     public void onCreate(Bundle savedInstanceState) {  
     9         super.onCreate(savedInstanceState);  
    10         setContentView(R.layout.main);  
    11         btnTest = (Button)this.findViewById(R.id.bt1);  
    12         textView = (EditText)this.findViewById(R.id.ed1);  
    13           
    14         btnTest.setOnClickListener(new View.OnClickListener() {  
    15               
    16             @Override  
    17             public void onClick(View arg0) {  
    18                   
    19                 Looper looper = Looper.getMainLooper(); //主线程的Looper对象  
    20                 //这里以主线程的Looper对象创建了handler,  
    21                 //所以,这个handler发送的Message会被传递给主线程的MessageQueue。  
    22                 handler = new MyHandler(looper);  
    23                 handler.removeMessages(0);  
    24                 //构建Message对象  
    25                 //第一个参数:是自己指定的message代号,方便在handler选择性地接收  
    26                 //第二三个参数没有什么意义  
    27                 //第四个参数需要封装的对象  
    28                 Message msg = handler.obtainMessage(1,1,1,"主线程发消息了");  
    29                   
    30                 handler.sendMessage(msg); //发送消息  
    31                 Log.i(tag, looper.toString());  
    32                 Log.i(tag, msg.toString());  
    33                 Log.i(tag, handler.toString());  
    34             }  
    35         });  
    36     }  
    37       
    38     class MyHandler extends Handler{  
    39           
    40         public MyHandler(Looper looper){  
    41             super(looper);  
    42         }  
    43           
    44         public void handleMessage(Message msg){  
    45             super.handleMessage(msg);  
    46             textView.setText("我是主线程的Handler,收到了消息:"+(String)msg.obj);  
    47         }  
    48     }  
    49 }

    2,其他线程给主线程发消息

     1 public class handler2 extends Activity{  
     2   
     3         private Button btnTest;  
     4         private EditText textView;  
     5 //      private final String tag="hyj_handler2";  
     6         private Handler handler;  
     7  /** Called when the activity is first created. */  
     8  @Override  
     9  public void onCreate(Bundle savedInstanceState) {  
    10      super.onCreate(savedInstanceState);  
    11      setContentView(R.layout.layout2);  
    12      btnTest = (Button)this.findViewById(R.id.bt2);  
    13      textView = (EditText)this.findViewById(R.id.ed2);  
    14        
    15      btnTest.setOnClickListener(new View.OnClickListener() {  
    16            
    17          @Override  
    18          public void onClick(View arg0) {  
    19                
    20              //可以看出这里启动了一个线程来操作消息的封装和发送的工作  
    21              //这样原来主线程的发送就变成了其他线程的发送,简单吧?呵呵  
    22              new MyThread().start();    
    23          }  
    24      });  
    25  }  
    26    
    27  class MyHandler extends Handler{  
    28        
    29      public MyHandler(Looper looper){  
    30          super(looper);  
    31      }  
    32        
    33      public void handleMessage(Message msg){  
    34          super.handleMessage(msg);  
    35          textView.setText("我是主线程的Handler,收到了消息:"+(String)msg.obj);  
    36      }  
    37  }  
    38  class MyThread extends Thread{  
    39        
    40      public void run(){  
    41          Looper looper = Looper.getMainLooper(); //主线程的Looper对象  
    42          //这里以主线程的Looper对象创建了handler,  
    43          //所以,这个handler发送的Message会被传递给主线程的MessageQueue。  
    44          handler = new MyHandler(looper);  
    45          Message msg = handler.obtainMessage(1,1,1,"其他线程发消息了");        
    46          handler.sendMessage(msg); //发送消息              
    47      }  
    48  }  
    49 }

     

    3,主线程给其他线程发消息

     1 public class handler3 extends Activity{  
     2     private Button btnTest;  
     3     private EditText textView;  
     4       
     5     private Handler handler;  
     6       
     7     @Override  
     8     public void onCreate(Bundle savedInstanceState) {  
     9         super.onCreate(savedInstanceState);  
    10         setContentView(R.layout.main);  
    11           
    12         btnTest = (Button)this.findViewById(R.id.bt1);  
    13         textView = (EditText)this.findViewById(R.id.ed1);  
    14           
    15           
    16         //启动线程  
    17         new MyThread().start();      
    18           
    19         btnTest.setOnClickListener(new View.OnClickListener() {  
    20               
    21             @Override  
    22             public void onClick(View arg0) {  
    23                 //这里handler的实例化在线程中  
    24                 //线程启动的时候就已经实例化了  
    25                 Message msg = handler.obtainMessage(1,1,1,"主线程发送的消息");  
    26                 handler.sendMessage(msg);  
    27             }  
    28         });  
    29     }  
    30       
    31     class MyHandler extends Handler{  
    32           
    33         public MyHandler(Looper looper){  
    34             super(looper);  
    35         }  
    36           
    37         public void handleMessage(Message msg){  
    38             super.handleMessage(msg);  
    39             textView.setText("我是主线程的Handler,收到了消息:"+(String)msg.obj);  
    40         }  
    41     }  
    42       
    43     class MyThread extends Thread{  
    44           
    45         public void run(){  
    46             Looper.prepare(); //创建该线程的Looper对象,用于接收消息  
    47               
    48             //注意了:这里的handler是定义在主线程中的哦,呵呵,  
    49             //前面看到直接使用了handler对象,是不是在找,在什么地方实例化的呢?  
    50             //现在看到了吧???呵呵,开始的时候实例化不了,因为该线程的Looper对象  
    51             //还不存在呢。现在可以实例化了  
    52             //这里Looper.myLooper()获得的就是该线程的Looper对象了  
    53             handler = new ThreadHandler(Looper.myLooper());  
    54               
    55             //这个方法,有疑惑吗?  
    56             //其实就是一个循环,循环从MessageQueue中取消息。  
    57             //不经常去看看,你怎么知道你有新消息呢???  
    58             Looper.loop();   
    59   
    60         }  
    61           
    62         //定义线程类中的消息处理类  
    63         class ThreadHandler extends Handler{  
    64               
    65             public ThreadHandler(Looper looper){  
    66                 super(looper);  
    67             }  
    68               
    69             public void handleMessage(Message msg){  
    70                 //这里对该线程中的MessageQueue中的Message进行处理  
    71                 //这里我们再返回给主线程一个消息  
    72                 handler = new MyHandler(Looper.getMainLooper());  
    73                   
    74                 Message msg2 = handler.obtainMessage(1,1,1,"子线程收到:"+(String)msg.obj);  
    75                   
    76                 handler.sendMessage(msg2);  
    77             }  
    78         }  
    79     } 

    4,其他线程给其自己发消息

     1 public class handler4 extends Activity{  
     2     Button bt1 ;  
     3     EditText et1;  
     4     Handler handler;  
     5     public void onCreate(Bundle savedInstanceState){  
     6         super.onCreate(savedInstanceState);  
     7         setContentView(R.layout.main);  
     8         bt1 = (Button)findViewById(R.id.bt1);  
     9         et1 = (EditText)findViewById(R.id.ed1);  
    10           
    11         bt1.setOnClickListener(new View.OnClickListener() {  
    12               
    13             @Override  
    14             public void onClick(View v) {  
    15                 new ThreadHandler().start();  
    16             }  
    17         });  
    18           
    19           
    20     }  
    21       
    22 class MyHandler extends Handler{  
    23           
    24         public MyHandler(Looper looper){  
    25             super(looper);  
    26         }  
    27           
    28         public void handleMessage(Message msg){  
    29             super.handleMessage(msg);  
    30             et1.setText("我是主线程的Handler,收到了消息:"+(String)msg.obj);  
    31         }  
    32     }  
    33       
    34  public class ThreadHandler extends Thread{  
    35         public void run(){  
    36             Looper.prepare();  
    37             handler = new Handlerthread(Looper.myLooper());  
    38             Message msg = handler.obtainMessage(1,1,1,"我自己");  
    39             handler.sendMessage(msg);  
    40             Looper.loop();  
    41         }  
    42           
    43         //定义线程类中的消息处理类  
    44        public class Handlerthread extends Handler{     
    45             public Handlerthread(Looper looper){  
    46                 super(looper);  
    47             }  
    48               
    49             public void handleMessage(Message msg){  
    50                 //这里对该线程中的MessageQueue中的Message进行处理  
    51                 //这里我们再返回给主线程一个消息  
    52                 //加入判断看看是不是该线程自己发的信息  
    53                 if(msg.what == 1 && msg.obj.equals("我自己")){  
    54                     handler = new MyHandler(Looper.getMainLooper());    
    55                     Message msg2 = handler.obtainMessage(1,1,1,"禀告主线程:我收到了自己发给自己的Message");          
    56                     handler.sendMessage(msg2);             
    57                 //et1.setText("++++++threadhandler"+(String)msg.obj);  
    58               
    59         }}  
    60        }  
    61           
    62     }  
    63 

    转自紫璐宇的专栏

  • 相关阅读:
    24. Swap Nodes in Pairs
    49. Group Anagrams
    280. Wiggle Sort
    274. H-Index
    K Closest Numbers In Sorted Array
    Closest Number in Sorted Array
    Last Position of Target
    Classical Binary Search
    350. Intersection of Two Arrays II
    Sort Integers II
  • 原文地址:https://www.cnblogs.com/chenbin7/p/2642628.html
Copyright © 2011-2022 走看看