首先,我们先看下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. Bootstrap3.0学习第七轮(按钮)

    详情请查看http://aehyok.com/Blog/Detail/13.html 个人网站地址:aehyok.com QQ 技术群号:206058845,验证码为:aehyok 本文文章链接:ht ...

  2. 【Moqui业务逻辑翻译系列】Story of Online Retail Company 在线零售公司的故事

    h1. Story of Online Retail Company 在线零售公司的故事 Someone decides to sell a product. [Product Marketer Ma ...

  3. 使用Git进行代码管理

    Git简介 Git 是 Linux Torvalds 为了帮助管理 Linux® 内核开发而开发的一个开放源码的版本控制软件. 先讲一下如何把开源项目fork到自己的github中 1.  点击图中的 ...

  4. shell--题目

    1.有一个文件,里面有二列,第一列ip地址,第二列是时间,同一个ip可能出现多次,但时间不同. 文件类似下面的样子: 192.168.1.2              13:10 192.127.12 ...

  5. 【poj1740】 A New Stone Game

    http://poj.org/problem?id=1740 (题目链接) 男人八题之一 题意 对于n堆石子,每堆若干个,两人轮流操作,每次操作分两步,第一步从某堆中去掉至少一个,第二步(可省略)把该 ...

  6. jQuery EasyUI API 中文文档

    http://www.cnblogs.com/Philoo/tag/jQuery/ 共2页: 1 2 下一页  jQuery EasyUI API 中文文档 - 树表格(TreeGrid) 风流涕淌 ...

  7. sdk和ndk

    让我先来说说android sdk (Android Software Development Kit, 即Android软件开发工具包)可以说只要你使用java去开发Android这个东西就必须用到 ...

  8. 如何使用MASM来编译、连接、调试汇编语言

    先声明下,本人绝非大虾,也只是菜鸟一个,写此文的目的只是为了加深我对知识的理解罢了.好,进入正题.我是把masm解压后发在D盘中的一个叫masm的文件里,在masm文件里新建个记事本(记事本功能是很强 ...

  9. 代码重构-3 用Tuple代替 out与ref

    返回单一值是良好的编程习惯 原代码: public LotteryViewModel ValidateLottery(LotteryBaseData baseData, int authTime, o ...

  10. 在ECSHOP后台左侧导航中增加新菜单

    在ECSHOP后台左侧导航中增加新菜单 ECSHOP教程/ ecshop教程网(www.ecshop119.com) 2011-11-08   有个别高级用户(懂PHP的),提到这样的问题: 在后台管 ...