1.使用handler循环往外抛消息检测
public void startDetect(long initialDelay, long period){
Handler handler = new Handler(Looper.getMainLooper());
runnable = new Runnable() {
@Override
public void run() {
if(满足条件) {
doTask();
return;
}
handler.postDelayed(runnable, 100);
}
};
handler.post(runnable);
}
2.java中的方法,一个死循环,然后使用sleep隔一段时间检测一下
public class sleepTask {
static volatile Boolean isInterrupt = false;
public static void main(String[] args) {
TimerTask task = new TimerTask() {
@Override
public void run() {
isInterrupt = true;
}
};
Timer timer = new Timer();
timer.schedule(task, 1000);
Runnable runnable = new Runnable() {
@Override
public void run() {
while (true) {
if (isInterrupt) {
System.out.println("execute task");
Thread.currentThread().interrupt();
return;
} else {
try {
Thread.sleep(250);
System.out.println("waitting ...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
}