[置顶] 在Android UI线程中执行定时任务的方法

时间:2022-03-22 18:29:50

         在项目中,我们经常会碰见执行定时任务的情况,比如下面这个场景:在2秒内连续点击两次返回键,应用就退出。这个功能实现的思路大体这样:定义一个类变量goback,记录点击的次数,如果2秒内点击了2次就finish,如果没有,goback就被重置为0,其中一种实现方法如下(1.0):

<span style="white-space:pre"></span>new Handler().postDelayed(new Runnable() {
@Override
public void run() {
goback = 0;
}
}, 2000);
接下来,我再探讨一下其他实现上面功能的方法:

1.1使用 ScheduledExecutorService

private static final ScheduledExecutorService worker = 
Executors.newSingleThreadScheduledExecutor();

Runnable task = new Runnable() {
public void run() {
/* Do something… */
}

worker
.schedule(task, 2, TimeUnit.SECONDS);


1.2 使用Timer类

new Timer().schedule(new TimerTask() { 
@Override
public void run() {
// this code will be executed after 2 seconds
}
}, 2000);

1.3还是使用handler,不过增加了message的发送

Handler myHandler = new DoSomething();
Message m = new Message();
m
.obj = c;//passing a parameter here
myHandler
.sendMessageDelayed(m, 1000);

class DoSomething extends Handler {
@Override
public void handleMessage(Message msg) {
MyObject o = (MyObject) msg.obj;
//do something here
}
}

1.4最后一种使用Thread类,有点繁琐,不建议用

private static long SLEEP_TIME = 2 // for 2 second
.
.
MyLauncher launcher = new MyLauncher();
launcher
.start();
.
.
private class MyLauncher extends Thread {
@Override
/**
* Sleep for 2 seconds as you can also change SLEEP_TIME 2 to any.
*/

public void run() {
try {
// Sleeping
Thread.sleep(SLEEP_TIME * 1000);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
//do something you want to do
//And your code will be executed after 2 second
}
}

差不多就是以上五种做法,各有各的适用场景,代码比较简单,不多说,直接拿过去用就行。