Handler主要是接收子线程式发送出消息,之后更新主线程UI。使用Handler时,可以通这子类继承Handler或者创建Handler内部在,但是两种都江堰市需要得写handleMessage(Message msg)方法,该方法接收数据
二、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对象到队列中,等待更新.
************
import android.view.KeyEvent;
import android.widget.TextView;
public class BundleActivity extends Activity
{
Handler hd=new Handler()
{
//重写handleMessage方法
public void handleMessage(Message msg)
{
switch(msg.what)//判断传入的消息
{
case 0:
Bundle b=msg.getData();
String str=b.getString("msg");//获取Bundle对象
tv.setText(str);//文本提示
break;
}
}
};
TextView tv;
public void onCreate(Bundle savedInstanceState)//继承Activity类重写的方法
{
super.onCreate(savedInstanceState);//调用父类
setContentView(R.layout.main);//显示当前的布局
tv=(TextView)findViewById(R.id.textView2);//实例化视图
new MyThread(this).start();//开始线程
}
public boolean onKeyDown(int KeyCode,KeyEvent event)//重写onKeyDown方法
{
if(KeyCode==4)
{
System.exit(0);//退出
}
return true;
}
}
******************************************************************
package com.bundle;
import android.os.Bundle;
import android.os.Message;
public class MyThread extends Thread
{
int count;//计数
BundleActivity activity;//主控制类的引用
boolean flag=true;
public MyThread(BundleActivity activity)//构造方法
{
this.activity=activity;
}
public void run()//继承Thread类需要重写的run方法
{
while(flag)
{
if(count>=10)
{
flag=false;
}
String msg="第"+(count++)+"次更改TextView的文字。";
Bundle bd=new Bundle();//创建Bundle对象
bd.putString("msg", msg);//向Bundle添加数据
Message message=new Message();//创建Message对象
message.setData(bd);//向Message中添加数据
message.what=0;
activity.hd.sendMessage(message);//调用主控制类中的Handler对象发送消息
try
{
Thread.sleep(3000);//让线和休眠3秒
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
*******************************************************************************
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/bnkj"
>
<TextView android:text="通过有消息循环的线程定时修改TextView的显示!"
android:textColor="#FFFFFF"
android:textSize="20dip"
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TextView>
<TextView android:text="未接收任何消息!"
android:textColor="#FF3300"
android:textSize="20dip"
android:layout_marginTop="20dip"
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>