Android Handler总结1-定义与用法

Handler是什么?

先来看看Android官网的描述:
A Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it – from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

翻译过来就是:
Handler是用来结合线程的消息队列来发送、处理Message对象和Runnable对象的工具。每一个Handler实例之后会关联一个线程和该线程的消息队列。当你创建一个Handler的时候,从这时开始,它就会自动关联到所在的线程/消息队列,然后它就会陆续把Message/Runnalbe分发到消息队列,并在它们出队的时候处理掉。

总结来说,就是Handler是一个工具,一个用来发送和处理Message和Runnable对象的工具。

Handler的作用

官网描述如下:
There are two main uses for a Handler: (1) to schedule messages and runnables to be executed at some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.

翻译过来就是:
handler有两个主要用途:
1、推送未来某个时间点将要执行的Message或者Runnable到消息队列。
2、在子线程把需要在另一个线程执行的操作加入到消息队列中去。

Handler使用方法

1、推送未来某个时间点将要执行的Message或者Runnable到消息队列。
方法一:Handler+Message

public class MainActivity extends AppCompatActivity {

    private String TAG = "testHandler";
    private Button testBtn;
   
   //忽略此处的内存泄漏
    private Handler myHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            testBtn.setText(msg.what+"");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        testBtn = (Button) findViewById(R.id.sample_text);
        testBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                for (int i = 0; i < 60; i++) {
                    Message message = Message.obtain(myHandler);
                    message.what = 60 - i;
                    myHandler.sendMessageDelayed(message, i * 1000);
                }
            }
        });
    }
}

方式二:Handler+Runnable

public class MainActivity extends AppCompatActivity {

    private String TAG = "testHandler";
    private Button testBtn;

    private Handler myHandler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        testBtn = (Button) findViewById(R.id.sample_text);
        testBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                for (int i = 0; i < 60; i++) {
                    final int time = 60 - i;
                    myHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                           //此处并不是在新的线程中,该线程和Handler所在线程一致
                            testBtn.setText(time + "");
                        }
                    }, i * 1000);
                }
            }
        });
    }
}

方式一和方式二本质上是一样的,因为Handler发送Runnable对象最后也会被转化成Message对象。

实际开发中我们可以这样处理:如果传输的数据较复杂可以使用Handler+Message的方式,如果需要执行的操作简单则使用Handler+Runnable的方式。

2、在子线程把需要在另一个线程执行的操作加入到消息队列中去

public class MainActivity extends AppCompatActivity {

    private String TAG = "testHandler";
    private Button testBtn;

    private Handler myHandler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        testBtn = (Button) findViewById(R.id.sample_text);
        testBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 开启一个线程
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // 执行耗时的操作,比如复杂的计算,网络请求等;
                        ....
                        //通过Looper.getMainLooper()获取主线程(其他线程)的Handler
                        Handler handler = new Handler(Looper.getMainLooper());
                        // 通过Handler的post方法将Runnable对象发送到UI线程的MessageQueue中
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                // 在MessageQueue出队该Runnable时进行的操作
                                  testBtn.setText(time + "");
                            }
                        });
                    }
                }).start();

            }
        });
    }
}

你可能感兴趣的:(#,Android基础,#,Android总结与进阶)