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以后用到再写。