android handler 实现

来源:互联网 发布:如何进行数据分析 编辑:程序博客网 时间:2024/06/08 01:57
一、Handler的定义:

          主要接受子线程发送的数据, 并用此数据配合主线程更新UI.

          解释: 当应用程序启动时,Android首先会开启一个主线程 (也就是UI线程) , 主线程为管理界面中的UI控件,进行事件分发, 比如说, 你要是点击一个 Button ,Android会分发事件到Button上,来响应你的操作。  如果此时需要一个耗时的操作,例如: 联网读取数据,    或者读取本地较大的一个文件的时候,你不能把这些操作放在主线程中,,如果你放在主线程中的话,界面会出现假死现象, 如果5秒钟还没有完成的话,,会收到Android系统的一个错误提示  "强制关闭".  这个时候我们需要把这些耗时的操作,放在一个子线程中,因为子线程涉及到UI更新,,Android主线程是线程不安全的,也就是说,更新UI只能在主线程中更新,子线程中操作是危险的. 这个时候,Handler就出现了.,来解决这个复杂的问题 ,    由于Handler运行在主线程中(UI线程中),  它与子线程可以通过Message对象来传递数据, 这个时候,Handler就承担着接受子线程传过来的(子线程用sedMessage()方法传弟)Message对象,(里面包含数据)  , 把这些消息放入主线程队列中,配合主线程进行更新UI。

二、Handler一些特点

        handler可以分发Message对象和Runnable对象到主线程中, 每个Handler实例,都会绑定到创建他的线程中(一般是位于主线程),
        它有两个作用: (1):  安排消息或Runnable 在某个主线程中某个地方执行, (2)安排一个动作在不同的线程中执行
     
        Handler中分发消息的一些方法
        post(Runnable)
        postAtTime(Runnable,long)
        postDelayed(Runnable long)
        sendEmptyMessage(int)
        sendMessage(Message)
        sendMessageAtTime(Message,long)
        sendMessageDelayed(Message,long)

        以上post类方法允许你排列一个Runnable对象到主线程队列中,
        sendMessage类方法, 允许你安排一个带数据的Message对象到队列中,等待更新.

三、Handler实例

      (1) 子类需要继承Hendler类,并重写handleMessage(Message msg) 方法, 用于接受线程数据

      以下为一个实例,它实现的功能为 : 通过线程修改界面Button的内容
  1. public class MyHandlerActivity extends Activity {
  2.     Button button;
  3.     MyHandler myHandler;

  4.     protected void onCreate(Bundle savedInstanceState) {
  5.         super.onCreate(savedInstanceState);
  6.         setContentView(R.layout.handlertest);

  7.         button = (Button) findViewById(R.id.button);
  8.         myHandler = new MyHandler();
  9.         // 当创建一个新的Handler实例时, 它会绑定到当前线程和消息的队列中,开始分发数据
  10.         // Handler有两个作用, (1) : 定时执行Message和Runnalbe 对象
  11.         // (2): 让一个动作,在不同的线程中执行.

  12.         // 它安排消息,用以下方法
  13.         // post(Runnable)
  14.         // postAtTime(Runnable,long)
  15.         // postDelayed(Runnable,long)
  16.         // sendEmptyMessage(int)
  17.         // sendMessage(Message);
  18.         // sendMessageAtTime(Message,long)
  19.         // sendMessageDelayed(Message,long)
  20.      
  21.         // 以上方法以 post开头的允许你处理Runnable对象
  22.         //sendMessage()允许你处理Message对象(Message里可以包含数据,)

  23.         MyThread m = new MyThread();
  24.         new Thread(m).start();
  25.     }

  26.     /**
  27.     * 接受消息,处理消息 ,此Handler会与当前主线程一块运行
  28.     * */

  29.     class MyHandler extends Handler {
  30.         public MyHandler() {
  31.         }

  32.         public MyHandler(Looper L) {
  33.             super(L);
  34.         }

  35.         // 子类必须重写此方法,接受数据
  36.         @Override
  37.         public void handleMessage(Message msg) {
  38.             // TODO Auto-generated method stub
  39.             Log.d("MyHandler", "handleMessage......");
  40.             super.handleMessage(msg);
  41.             // 此处可以更新UI
  42.             Bundle b = msg.getData();
  43.             String color = b.getString("color");
  44.             MyHandlerActivity.this.button.append(color);

  45.         }
  46.     }

  47.     class MyThread implements Runnable {
  48.         public void run() {

  49.             try {
  50.                 Thread.sleep(10000);
  51.             } catch (InterruptedException e) {
  52.                 // TODO Auto-generated catch block
  53.                 e.printStackTrace();
  54.             }

  55.             Log.d("thread.......", "mThread........");
  56.             Message msg = new Message();
  57.             Bundle b = new Bundle();// 存放数据
  58.             b.putString("color", "我的");
  59.             msg.setData(b);

  60.             MyHandlerActivity.this.myHandler.sendMessage(msg); // 向Handler发送消息,更新UI

  61.         }
  62.     }

  63. }

以上代码是不实现消息队列和消息循环的,如果要实现消息队列和消息循环,需要加入Looper。

注意:默认情况下,线程是没有Looper的,所以要调用 Looper.prepare()来给线程创建消息循环,然后再通过,Looper.loop()来使消息循环起作用。

android 官方文档示例:

Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.

Most interaction with a message loop is through the Handler class.

This is a typical example of the implementation of a Looper thread, using the separation ofprepare() and loop() to create an initial Handler to communicate with the Looper.

 

class LooperThread extends Thread

{

public Handler mHandler;

public void run()

{

           Looper.prepare();

          mHandler = new Handler()

   {

    public void handleMessage(Message msg)

             {

                 // process incoming messages here

            }

   };

      Looper.loop();

}


 

 另外有一种方式是直接使用looper对像作为参数new一个hander对像:

Looper looper = (handler != null) ? handler.getLooper() : mMainLooper;

mHandler = new Handler(looper){

     public void handleMessage(Message msg) {

      }

};

Handler处理消息总是在创建Handler的线程里运行。而我们的消息处理中,不乏更新UI的操作,不正确的线程直接更新UI将引发异常。因此,需要时刻关心Handler在哪个线程里创建的。

如何更新UI才能不出异常呢?SDK告诉我们,有以下4种方式可以从其它线程访问UI线程:

·     Activity.runOnUiThread(Runnable)

·     View.post(Runnable)

·     View.postDelayed(Runnable, long)

·     Handler

其中重点说一下的是View.post(Runnable)方法。在post(Runnable action)方法里View获得当前线程UI线程Handler然后将action对象postHandler里。在Handler里,它将传递过来的action对象包装成一个MessageMessagecallbackaction),然后将其投入UI线程的消息循环中。在Handler再次处理该Message时,有一条分支(未解释的那条)就是为它所设,直接调用runnablerun方法。而此时,已经路由到UI线程里,因此,我们可以毫无顾虑的来更新UI

4 几点小结

·     Handler的处理过程运行在创建Handler的线程里

·     一个Looper对应一个MessageQueue

·     一个线程对应一个Looper

·     一个Looper可以对应多个Handler

·     不确定当前线程时,更新UI时尽量调用post方法

 

原创粉丝点击