淘宝(阿里百川)手机客户端开发日记第八篇 Handler的使用方法

时间:2023-03-08 22:32:07

首先,我们先看下API文档的说明:

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.

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

Scheduling messages is accomplished with the post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long), sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long), and sendMessageDelayed(Message, long) methods. The post versions allow you to enqueue Runnable objects to be called by the message queue when they are received; the sendMessage versions allow you to enqueue a Message object containing a bundle of data that will be processed by the Handler's handleMessage(Message) method (requiring that you implement a subclass of Handler).

中文翻译的大概意思是:

一个Handler允许你发送和处理消息和关联了消息队列的Runnable对象,每个handler 实例关联一个单一的线程和这个线程的消息队列;当你创建一个Handler,它绑定了创建它的线程有关的线程/消息队列,从那个点起,handler就开始处理这些数据并且执行出来的队列的消息。

对于一个handler,主要有2中用途:一个是调用在未来某个时刻执行消息,第二个是将一个action放进队列里被不同的线程执行而不是自己来处理。

如果调度消息使用post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long), sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long), and sendMessageDelayed(Message, long) 这些方法完成的,”POST"动作允许你将对象加入到消息队里当被获得的时候被调用,"sendMessage"动作允许你将带有附加的数据加入队列中,它将被handleMessage(Message)这个方法被处理。

更多详情的内容大家可以参考API说明文档。这里我们需要知道,handler如果不断的获取数据,我们需要向不断的向handler投递数据,即使用方法 post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long)

以上上Handler的官方简单的介绍。

然后,我们需要对Android的消息循环机制要有所了解。

我们在上节课中,大家看到,在一个线程里做循环,是得不到我们想要的结果的.因为Thread类在run()方法中的内容执行完之后就退出了,即线程做完自己的工作之后就结束了,没有循环的概念。线程和消息循环是没有关联的。

android 为我们提供了Loop类,它可以在一个线程里循环的执行消息的投送。官方给出的DEMO是:

 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();
       }  

 }

在下一节中,我们将对Loop内部进行深入学习,这里 我们使用了public final boolean postDelayed (Runnable r, long delayMillis)这个方法。

package com.example.servicedemo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class HandlerDemo extends Activity implements OnClickListener {
    private Button btnStart;
    private TextView tvCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler);

        btnStart = (Button)findViewById(R.id.btnStart);
        tvCount = (TextView)findViewById(R.id.tvCount);

        btnStart.setOnClickListener(this);
    }

    @Override
    public void onClick(View arg0) {
        Thread thread = new Thread(r);
        thread.start();
    }

    Handler handler = new Handler()
    {
        public void handleMessage(Message msg) {
            if(msg.what != 100)
            {
                tvCount.setText(String.valueOf(msg.what));
            }
        }
    };

    Runnable r = new Runnable() {
        int i = 0;
        public void run() {
            i = i + 1;
            Message msg = handler.obtainMessage();
            msg.what= i ;
            System.out.println("i--->" + i);
            if(i==100){
                handler.removeCallbacks(r);
            }
            else
            {
                  handler.sendMessage(msg);
                  //过一秒钟后,handler又调用了run里的方法
                  handler.postDelayed(r, 1000);
            }

       }
    };

}

在此运行后的结果就是数字在不断的加1了,同时控制台的打印结果也显示了1秒后继续执行Run中的方法:

淘宝(阿里百川)手机客户端开发日记第八篇 Handler的使用方法

淘宝(阿里百川)手机客户端开发日记第八篇 Handler的使用方法

转载请注明http://www.cnblogs.com/yushengbo,否则将追究版权责任!