Handler 的简单使用

view和控件不是线程安全的  


Handler的官方描述:


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


新手一枚,方便查阅,所以写到博客里,以便自己以后复习用,有写错的地方欢迎高手指正。


今天简单的测试了下,用Handler处理2个Runnable ,一个是控制进度条在10秒钟完成100,一个是每隔5秒钟换一下背景图片。

	int[] back={R.drawable.p1,R.drawable.p3};
	int index=0;
	//背景图片的设置
	Runnable r=new Runnable() {
	@Override
	public void run() {
		if(index>1)
			index=0;
		getWindow().setBackgroundDrawableResource(back[index++]);
		h.postDelayed(r, 5000);
	}
};
//进度条测试
int count=0;
Runnable rr=new Runnable() {
	
	@Override
	public void run() {
		
		if(count<100){
		pb.setProgress(++count);
		h.postDelayed(rr, 100);
		}
		else{
			h.removeCallbacks(rr);
		}
	}
};
	Handler h=new Handler();
	ProgressBar pb;
Handler h=new Handler();

pb=(ProgressBar) findViewById(R.id.pb1);
		h.post(r);
		h.post(rr);

今天的老师给留的考试题,就简单的做下这个,至于 sendMessage以后用到再写。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值