Handler 的使用解析

Handler 有两种使用方式,一个是Post,一个是sendMessage。

post方式

  • post(Runnable r): 一般的post方式。
  • postAtTime(Runnable r, long uptimeMillis):设置在某一个绝对时间执行
  • postAtTime(Runnable r, Object token, long uptimeMillis)
  • postDelayed(Runnable r, long delayMillis):设置延迟执行时间执行

定一个Handler

private Handler mPostHandler = new Handler();

起一个子线程:

private class TestThread extends Thread{
    @Override
    public void run() {

        try {
            Thread.sleep(5000);


            /**
             * Post允许把一个Runnable对象入队到消息队列中.
             * 方法有:
             * post(Runnable)
             * postAtTime(Runnable,long)
             * postDelayed(Runnable,long)
             *
             * 对于Handler的Post方式来说,它会传递一个Runnable对象到消息队列中,在这个Runnable对象中,重写run()方法。一般在这个run()方法中写入需要在UI线程上的操作。
             */
            mPostHandler.post(new Runnable() {
                @Override
                public void run() {
                    text.setText("Handler的Post方式到主线程");
                    LogHelper.i("Handler的Post方式到主线程");
                }
            });

            /**
             * postAtTime: 在设置的某一个绝对时间执行。
             */
            mPostHandler.postAtTime(new Runnable() {
                @Override
                public void run() {
                    text.setText(text.getText().toString()+"\n Handler的postAtTime方式到主线程");
                    LogHelper.i("Handler的postAtTime方式到主线程");
                }
            }, SystemClock.uptimeMillis() + 5000);

            /**
             * postDelayed:延迟执行.
             */
            mPostHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    text.setText(text.getText().toString()+"\n Handler的postDelayed方式到主线程");
                    LogHelper.i("Handler的postDelayed方式到主线程");
                }
            },1000);



        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

sendMessage 方式

首先要在Handler中处理Message:

  • sendMessage(Message msg):

  • sendMessageDelayed(Message msg, long delayMillis):

  • sendMessageAtTime(Message msg, long uptimeMillis) :

  • sendEmptyMessage(int what)

  • sendEmptyMessageDelayed(int what, long delayMillis)

  • sendEmptyMessageAtTime(int what, long uptimeMillis) :

    private Handler mHandler = new Handler(){

      @Override
      public void handleMessage(Message msg) {
          switch (msg.what){
              case MSG_ONE:
                  String obj = (String)msg.obj;
                  LogHelper.i("\n obj is : " + obj);
                  text.setText(text.getText().toString()+"obj is : " + obj);
    
                  int arg1 = msg.arg1;
                  int arg2 = msg.arg2;
                  LogHelper.i("\n arg1 is : " + arg1 + " arg2 is : " + arg2);
                  text.setText(text.getText().toString()+"arg1 is : " + arg1 + " arg2 is : " + arg2);
    
                  if(msg.getData() != null){
                     String test =  (String)msg.getData().get("test");
                      LogHelper.i("\n test is : " + test);
                      text.setText(text.getText().toString()+"test is : " + test);
                  }
                  break;
              case MSG_TWO:
                  LogHelper.i("receive  MSG_TWO ");
                  break;
          }
      }
    

    };

创建子线程

private class TestMessageThread extends Thread {
    @Override
    public void run() {

        try {
            Thread.sleep(5000);

            /**
             * 有3中方式获取Message:
             *
             * 1、Message message = new Message();
             * 2、Message message = Message.obtain();
             * 3、Message message = mHandler.obtainMessage();
             *
             */
            Message message = Message.obtain();

            /**
             * what是我们自定义的一个Message的识别码,以便于在Handler的handleMessage方法中根据what识别出不同的Message,以便我们做出不同的处理操作
             */
            message.what = MSG_ONE;

            /**
             * 可以通过arg1和arg2给Message传入简单的数据
             */
            message.arg1 = 100;
            message.arg2 = 101;

            /**
             * 可以通过给obj赋值Object类型传递向Message传入任意数据
             */
            message.obj = new String("Obj String");

            /**
             * 通过setData方法和getData方法向Message中写入和读取Bundle类型的数据
             */
            Bundle bundle = new Bundle();
            bundle.putString("test","test string");
            message.setData(bundle);

            mCallHandler.sendMessage(message);
            /**
             * 传递空消息。
             */
            mCallHandler.sendEmptyMessage(MSG_TWO);

            /**
             * 在设置的某一个绝对时间执行。
             */
            mHandler.sendMessageAtTime(message,SystemClock.uptimeMillis() + 5000);

            /**
             * 延迟执行
             */
            mHandler.sendMessageDelayed(message,1000);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

Handler中还有一种带Callback的构造函数:

/**
 * Callback 回调如果返回的是true,则不往下执行,如果返回的是false,则会继续执行下面的handleMessage,达到拦截的效果.
 */
private Handler mCallHandler = new Handler(new Handler.Callback() {
    @Override
    public boolean handleMessage(Message msg) {
        if(msg.what == MSG_TWO){
            LogHelper.i("Callback  MSG_TWO ");
            return true;
        }
        return false;
    }
}){
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what){
            case MSG_ONE:
                String obj = (String)msg.obj;
                LogHelper.i("\n obj is : " + obj);
                text.setText(text.getText().toString()+"obj is : " + obj);

                int arg1 = msg.arg1;
                int arg2 = msg.arg2;
                LogHelper.i("\n arg1 is : " + arg1 + " arg2 is : " + arg2);
                text.setText(text.getText().toString()+"arg1 is : " + arg1 + " arg2 is : " + arg2);

                if(msg.getData() != null){
                    String test =  (String)msg.getData().get("test");
                    LogHelper.i("\n test is : " + test);
                    text.setText(text.getText().toString()+"test is : " + test);
                }
                break;
            case MSG_TWO:
                LogHelper.i("receive  MSG_TWO ");
                break;
        }
    }
};

你可能感兴趣的:(Handler 的使用解析)