Handler定时器,每隔5s执行一次task任务,task任务在主线程中执行
①
/**
* 任务
*/
private Runnable task = new Runnable() {
@Override
public void run() {
// 此处执行任务 此处即使界面返回也会一直后台运行
Log.i("djtest", "run: 该条打印信息仅测试锁屏情况下是否会执行task内容");
// 每5s重复一次
handler.postDelayed(this, 5 * 1000);//延迟5秒,再次执行task本身,实现了5s一次的循环效果
}
};
②
/**
* 接收、分析、执行模块
*/
@SuppressLint("HandlerLeak")
Handler handler = new Handler() {
@SuppressLint("SetTextI18n")
public void handleMessage(Message msg) {
if (msg.what == 0x66) {
} else if (msg.what == 0x44) {
} else if (msg.what == 0x11) {
} else {
}
}
};
③
在oncreate中首次调用
handler.postDelayed(task, 1000); // 第一次调用,延迟1秒执行task
Handler定时器,每隔5s执行一次task任务,task任务放在子线程中执行
① 在oncreate中启动子线程:
new NetWorkThread().start();
② 子线程中调用task任务:
public class NetWorkThread extends Thread {
@Override
public void run() {
super.run();
networkHandler.postDelayed(network_task, 5 * 1000);
Log.i(TAG, "NetWorkThread");
}
}
③ task任务:
private Runnable network_task = new Runnable() {
@Override
public void run() {
// 消息准备
Message message = networkHandler.obtainMessage();
// 耗时操作
if(TestNetwork.ping()) {
message.what = 1;
} else {
message.what = 2;
}
// 每5s重复一次
networkHandler.sendMessageDelayed(message, 5*1000);
}
};
④ handler接收并处理:
private Handler networkHandler = new Handler(){
@SuppressLint("HandlerLeak")
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) { //判断标志位
case 1:
//更新UI操作
Log.i(TAG, "run: 网络已连接");
tv_NoNetWork.setVisibility(View.GONE);
networkHandler.postDelayed(network_task,5000);
break;
case 2:
Log.i(TAG, "run: 网络未连接");
tv_NoNetWork.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, R.string.NoNetWork, Toast.LENGTH_LONG).show();
networkHandler.postDelayed(network_task,5000);
break;
}
}
};