欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用Runnable和Handler做定时任务

程序员文章站 2022-03-22 08:07:53
...
1.定义Handler:
    Handler onlineHandler = new Handler() {

@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.arg1) {
case 0: {
home_0.setImageResource(R.drawable.home_2_style);
break;
}
case 1: {
home_0.setImageResource(R.drawable.home_2_status_style);
break;
}
}
home_0.postInvalidate();
}

};

2,定义Runnable:
   Runnable onlineRunnable = new Runnable() {

@Override
public void run() {
Message m = new Message();
if (readRd() != null && readRd().trim().equals("0")) {
m.arg1 = 0;
} else {
m.arg1 = 1;
}
onlineHandler.sendMessage(m);
//每隔5秒执行一次
onlineHandler.postDelayed(onlineRunnable, 5000);
}

3.启动线程:
onlineHandler.post(onlineRunnable);
相关标签: code