Handler的简单使用(二)

Android线程和Java类似,都是有两种方法:
一个是直接继承Thread类,另一个是实现Runnable接口。

现在我们用Android实现计数,即界面上每过一秒数字便加1。

1.首先新建一个countThread类,让它继承Runnable接口,在该类重写run方法,在里面实现计数的功能,run方法中的内容如下:

@Override
	public void run() {
		for(int i=0;i<100;i++){
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String text = ""+i;
		}
		
	}

2.Handler处理线程的机制是使用一个消息队列,在队尾添加等待处理的消息,在队首处理消息,同时不断检查消息。
现在我们就需要将上面代码中的text中的内容添加到消息队列中去,在上面代码的后面添加上以下三行代码:

			Message msg = new Message();
			msg.obj = text;//消息内容为text,为object类型,处理消息时候需要进行强制类型转换,还可以使用msg.arg1,msg.arg2,不过它内容类型是int型
			handler.sendMessage(msg);//添加到消息队列中去

3.上面代码中的handler需要通过构造方法从DrawActivity中传递过来,这是因为在线程中不能创建Handler对象。
所以该countThread类的构造函数为:

	Handler handler;
	
	public countThread(Handler handler) {
		super();
		this.handler = handler;
	}

4.现在创建一个countHandler类来处理消息队列中的消息,其中需要重写处理消息的方法(public void handleMessage (Message msg){})
具体处理过程将取出的消息内容设置为TextView需要显示的内容。所以需要添加一个构造方法将组件TextView传递过来。
代码如下:

import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

public class counterHandler extends Handler{
	TextView text;
	public counterHandler(TextView text){
		this.text = text;
	} 
	//重写处理消息的方法
	public void handleMessage (Message msg){
		String s = (String)msg.obj;
		text.setText(s);
	}
}

5.在DrawActivity中实例化counterHandler以及countThread这两个类,将需要的参数传递过去,然后启动线程。
DrawActivity中的代码如下:

		TextView textview = (TextView)this.findViewById(R.id.textView1);
		Handler handler = new counterHandler(textview);
		countThread thread = new countThread(handler);
		new Thread(thread).start();

6.现在运行程序,运行结果如下计时后面的数字每过1秒自动加1
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42882887/article/details/86555801