首先,我们先看下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中的方法:

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

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

  1. 淘宝(阿里百川)手机客户端开发日记第十一篇 JSP+Servlet

    由于本人从事.net开发已有多年经验,今天由于工作需要,我只能学习下JSP+Servlet,至于java web提供了更好的开发框架MVC,现在由于时间关系,我只好用JSP+Servlet来搭建服务器 ...

  2. 淘宝(阿里百川)手机客户端开发日记第五篇 SharedPreferences使用详解

    我们知道,Android中数据存储技术由于如下几种 1 使用SharedPreferences存储数据 2 文件存储数据 3 SQLite数据库存储数据 4 使用ContentProvider存储数据 ...

  3. 淘宝(阿里百川)手机客户端开发日记第十篇 阿里百川服务器环境介绍之API文档的快速链接(四)

    个人感觉比较重要的快速链接: http://open.taobao.com/doc/detail.htm?id=102513 http://open.taobao.com/doc/detail.htm ...

  4. 淘宝(阿里百川)手机客户端开发日记第十三篇 mysql的连接

    首先,我建立了一个包,里面存放了三个类文件,这三个文件是我从网络中找的,经过自己的整理.(我刚才查找想把这三个文件传上去,可能是自己对cnblogs的博客不太熟悉吧,没有找到,我只好粘贴代码了) 三个 ...

  5. 淘宝(阿里百川)手机客户端开发日记第七篇 Service,Handler和Thread

    现在我们已经已经知道android有Service,Handler和Thread这些内容了,但是我想应该还有很多人对此并不是很清楚他们之间的区别! (1)Service 是运行在后端的程序,不与UI直 ...

  6. 淘宝(阿里百川)手机客户端开发日记第六篇 Service详解(六)

    Service和Thread的关系 不少初学者都可能会有这样的疑惑,Service和Thread到底有什么关系呢?什么时候应该用Service,什么时候又应该用Thread? 答案是Service和T ...

  7. 淘宝(阿里百川)手机客户端开发日记第六篇 Service详解(五)

    我们现在对上一节中的DEMO进行改进,在服务中开启线程来执行. package com.example.service; import android.app.Service; import andr ...

  8. 淘宝(阿里百川)手机客户端开发日记第六篇 Service详解(四)

    DEMO1:在Activity里声明一个回调方法,当service完成任务后,调用这个回调方法. 首先,我们先继承service,来创建服务,代码如下: package com.example.ser ...

  9. 淘宝(阿里百川)手机客户端开发日记第六篇 Service详解(三)

    主题:Service与Activity交互通信 问题的引出:现在有个需求,如果我们有一个下载任务,下载时间耗时比较长,并且当下载完毕后,需要更新UI的内容,这时,service中的bindServic ...

随机推荐

  1. cocos2d-x 3.0以上版本字体设置问题

    cocos2d-x中的万年大坑,字体总算是有比较好的结局办法了.之前都是CCLabelTTF,CCLabelBMFont,CCLabelAtlas什么的,我只想说一句:好难用!毕竟是做游戏,那么难看的 ...

  2. sql 随机函数newid()

    newid()返回的是uniqueidentifier类型的唯一值.newid()每次产生的值都不一样 从表中随机获取前N条记录 select top N *  from table_name ord ...

  3. 标准I/O

    在程序运行时,会默认为我们打开三个流:标准输入流.标准输出流.标准出错流. 标准输入流一般对应我们的键盘 标准输出流一般对应显示器 标准出错流一般也对应显示器 1.标准输入流 在标准I/O中,java ...

  4. Java 读取文件到字符串

    Java的io操作比较复杂 package cn.outofmemory.util; import java.io.BufferedReader; import java.io.FileInputSt ...

  5. 第十四章:Annotation(注释)

    一:注解 1.当成是一种修饰符吧,修饰类及类的所有成员. 代码里的特殊标记,这些标记可以在编译.类加载.运行时被读取. 2.@Override:强制子类覆盖(重写)父类的方法. @Deprecated ...

  6. Ajax、反向Ajax和WebSocket 概念

    Ajax 异步的JavaScript和XML(Asynchronous JavaScript and XML,Ajax),一种可通过JavaScript来访问的浏览器功能特性,其允许脚本向幕后的网站发 ...

  7. 图解Android - Binder 和 Service

    在 Zygote启动过程 一文中我们说道,Zygote一生中最重要的一件事就是生下了 System Server 这个大儿子,System Server 担负着提供系统 Service的重任,在深入了 ...

  8. sort+awk+uniq三者结合使用

    (1)统计文件中出现次数最多的前10个单词 #ps -ef > ps.file #cat ps.file | awk ‘{print $1}’ | sort | uniq -c | sort - ...

  9. 【ZOJ 3609】Modular Inverse

    题 题意 求a关于m的乘法逆元 分析 a x ≡ 1 (mod m) 等价于 ax+my=1 求x的最小正数(不能是0,我就WA在这里了). 当m=1时,或者 gcd(a,m)!=1 时x不存在. 所 ...

  10. BZOJ2654 tree

    Description 给你一个无向带权连通图,每条边是黑色或白色.让你求一棵最小权的恰好有need条白色边的生成树. 题目保证有解. Input 第一行V,E,need分别表示点数,边数和需要的白色 ...