我们都知道应用程序开启后,安卓会开启一个主线程(UI线程),主线程管理UI控件,进行事件分发。那为什么会出现Handler呢?

例如你要是点击一个 Button ,Android会分发事件到Button上,来响应你的操作。  如果此时需要一个耗时的操作,例如: 联网读取数据, 或者读取本地较大的一个文件的时候,你把这些操作放在主线程中, 如果5秒钟还没有完成的话,界面会出现假死现象,会收到Android系统的一个错误提示  "强制关闭"。  这个时候我们需要把这些耗时的操作,放在一个子线程中,因为子线程涉及到UI更新,Android主线程是线程不安全的, 也就是说,更新UI只能在主线程中更新,子线程中操作是危险的。 这个时候,安卓开发为了解决这个问题Handler就出现了。

handler可以分发Message对象和Runnable对象到主线程中, 每个Handler实例,都会绑定到创建他的线程中(一般是位于主线程),它有两个作用:

(1)安排消息或Runnable 在某个主线程中某个地方执行;

(2)安排一个动作在不同的线程中执行。

Handler分发消息的一些方法:

post(Runnable)

postAtTime(Runnable,long)

postDelayed(Runnable long)

sendEmptyMessage(int)

sendMessage(Message)

sendMessageAtTime(Message,long)

sendMessageDelayed(Message,long)

post类方法允许你排列一个Runnable对象到主线程队列中,

sendMessage类方法, 允许你安排一个带数据的Message对象到队列中,等待更新。

下面是一个简单的实例:

 package com.example.nihongdeng;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView; public class FrameLayoutTest extends Activity { private int currentColor=0;
final int []colors=new int[]
{
R.color.color1,
R.color.color2,
R.color.color3,
R.color.color4,
R.color.color5,
R.color.color6
};
final int []names=new int[]
{
R.id.view01,
R.id.view02,
R.id.view03,
R.id.view04,
R.id.view05,
R.id.view06
};
TextView []views=new TextView[names.length];
Handler handler=new Handler()
{
public void handleMessage(Message msg)//要接收数据必须重写此方法
{
if (msg.what==0x123)//接收到数据所进行的操作
{
for (int i=0;i<names.length;i++)
{
views[i].setBackgroundResource(colors[(i+currentColor)%colors.length]);
}
currentColor++;
}
super.handleMessage(msg);
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for (int i=0;i<names.length;i++)
{
views[i]=(TextView)findViewById(names[i]);
}
new Timer().schedule(
new TimerTask()
{ @Override
public void run() {
// TODO Auto-generated method stub
handler.sendEmptyMessage(0x123);
} },0,200);
}
}

这个例子的效果是实现一种霓虹灯的效果:

布局代码:

 <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">"
<TextView
android:id="@+id/view01"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="320px"
android:height="320px"
android:background="@color/color1"/>
<TextView
android:id="@+id/view02"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="280px"
android:height="280px"
android:background="@color/color2"/>
<TextView
android:id="@+id/view03"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="240px"
android:height="240px"
android:background="@color/color3"/>
<TextView
android:id="@+id/view04"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="200px"
android:height="200px"
android:background="@color/color4"/>
<TextView
android:id="@+id/view05"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="160px"
android:height="160px"
android:background="@color/color5"/>
<TextView
android:id="@+id/view06"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="120px"
android:height="120px"
android:background="@color/color6"/> </FrameLayout>

代码我们通过Timer类来实现一个线程:

Timer是一种定时器工具,用来在一个后台线程计划执行指定任务。它可以计划执行一个任务一次或反复多次。
TimerTask一个抽象类,它的子类代表一个可以被Timer计划的任务。

schedule的意思(时间表、进度表)

timer.schedule(task,1000, 1000); //task是所要执行的任务,延时1000ms后执行,1000ms执行一次。

以上案例则是不延时执行,每0.2秒发送一次消息,接收到消息后对UI界面进行更新。

Android开发之Handler的更多相关文章

  1. Android开发之Handler的用法(源码分享)

    Handler主要接受子线程发送的数据, 并用此数据配合主线程更新UI.. 当应用程序启动时.Android首先会开启一个主线程 (也就是UI线程) , 主线程为管理界面中的UI控件,进行事件分发. ...

  2. Android开发之Handler和Looper的关系

              关于Handler的总结. Message:消息,当中包括了消息ID,消息处理对象以及处理的数据等,由MessageQueue统一列队,终由Handler处理. Handler:处 ...

  3. Android开发之bindService()侦听service内部状态

    在Android开发之bindService()通信的基础上,实现bindService()方法侦听service内部状态. 实现侦听service内部状态,使用的是回调机制 1.首先实现一个接口 p ...

  4. Android开发之Java集合类性能分析

    对于Android开发者来说深入了解Java的集合类很有必要主要是从Collection和Map接口衍生出来的,目前主要提供了List.Set和 Map这三大类的集合,今天Android吧(ard8. ...

  5. Android开发之InstanceState详解

    Android开发之InstanceState详解   本文介绍Android中关于Activity的两个神秘方法:onSaveInstanceState() 和 onRestoreInstanceS ...

  6. Android开发之Git配置

    Android开发之Git配置 1.首先git配置: 输入命令: git config --global user.name "xxx.xx" git config --globa ...

  7. 【Android UI】Android开发之View的几种布局方式及实践

    引言 通过前面两篇: Android 开发之旅:又见Hello World! Android 开发之旅:深入分析布局文件&又是“Hello World!” 我们对Android应用程序运行原理 ...

  8. Android开发之旅: Intents和Intent Filters(理论部分)

    引言 大部分移动设备平台上的应用程序都运行在他们自己的沙盒中.他们彼此之间互相隔离,并且严格限制应用程序与硬件和原始组件之间的交互. 我们知道交流是多么的重要,作为一个孤岛没有交流的东西,一定毫无意义 ...

  9. Android开发之ViewPager+ActionBar+Fragment实现响应式可滑动Tab

     今天我们要实现的这个效果呢,在Android的应用中十分地常见,我们可以看到下面两张图,无论是系统内置的联系人应用,还是AnyView的阅读器应用,我们总能找到这样的影子,当我们滑动屏幕时,Tab可 ...

随机推荐

  1. 基于WebForm+EasyUI的业务管理系统形成之旅 -- 系统设置(Ⅰ)

    上篇<基于WebForm+EasyUI的业务管理系统形成之旅 -- 总体介绍>,主要介绍系统总体的界面效果和用户体验UI设计. 在MVC.MVP大行其道的今天,写WebForm该系列篇章, ...

  2. 一步步写STM32 OS【二】环境搭建

    一.安装IAR for ARM6.5 二.新建工程 1.选择处理器:STM32F407VG,暂不使用FPU 2.必要的路径配置和宏定义 3.使用SWO重定向IO输出 4.使用ST-LINK仿真器 5. ...

  3. diamond专题(三)—— diamond架构

    大家好,这次为大家带来的是diamond的架构,架构如下图所示: 对该图进行一些说明: 1.作为一个配置中心,diamond的功能分为发布和订阅两部分.因为diamond存放的是持久数据,这些数据的变 ...

  4. Oracle 新增表空间文件

    ALTER TABLESPACE users ADD DATAFILE 'D:/oracle/oradata/orcl/users.dbf' SIZE 500M AUTOEXTEND ON NEXT ...

  5. NOIP2003 侦探推理

    题二    侦探推理 [问题描述] 明明同学最近迷上了侦探漫画<柯南>并沉醉于推理游戏之中,于是他召集了一群同学玩推理游戏.游戏的内容是这样的,明明的同学们先商量好由其中的一个人充当罪犯( ...

  6. vijosP1164 曹冲养猪

    vijosP1164 曹冲养猪 链接:https://vijos.org/p/1164 [思路] 数学. 如果x不能满足模公式则+gcd,gcd=a的积(a互质)使加上gcd后依然满足前面的模公式. ...

  7. 【Java基础】基础概念

    Java 关键字 被Java语言赋予特定含义的单词  组成关键字的字母全部小写  goto和const作为保留字存在,目前并不使用 一般关键字在IDE中会高亮 用于定义数据类型的关键字 class i ...

  8. .NET Compact Framework Data Provider for SQL Server CE

    .NET Compact Framework Data Provider for SQL Server Mobile Standard Data Source=MyData.sdf;Persist S ...

  9. guslterFS

    Installing GlusterFS - a Quick Start Guide Purpose of this document This document is intended to giv ...

  10. javascript中的function对象

    function对象都是Function的实例: > Object.getOwnPropertyNames(Function) [ 'length', 'name', 'arguments', ...