我希望能够在指定的延迟后调用以下方法。 在objective c中,有这样的东西:
[self performSelector:@selector(DoSomething) withObject:nil afterDelay:5];
在android和java中是否有类似的方法? 例如,我需要能够在5秒后调用一个方法。
public void DoSomething()
{
//do something here
}
我希望能够在指定的延迟后调用以下方法。 在objective c中,有这样的东西:
[self performSelector:@selector(DoSomething) withObject:nil afterDelay:5];
在android和java中是否有类似的方法? 例如,我需要能够在5秒后调用一个方法。
public void DoSomething()
{
//do something here
}
当前回答
有很多方法可以做到这一点,但最好的是使用如下处理程序
long millisecDelay=3000
Handler().postDelayed({
// do your work here
},millisecDelay)
其他回答
我创建了一个更简单的方法来调用它。
public static void CallWithDelay(long miliseconds, final Activity activity, final String methodName)
{
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
try {
Method method = activity.getClass().getMethod(methodName);
method.invoke(activity);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}, miliseconds);
}
要使用它,只需调用:.CallWithDelay(5000,这个,"DoSomething");
Kotlin & Java多种方式
1. 使用处理程序
Handler().postDelayed({
TODO("Do something")
}, 2000)
2. 使用TimerTask
Timer().schedule(object : TimerTask() {
override fun run() {
TODO("Do something")
}
}, 2000)
或者更短
Timer().schedule(timerTask {
TODO("Do something")
}, 2000)
或者说最短的是
Timer().schedule(2000) {
TODO("Do something")
}
3.使用执行人
Executors.newSingleThreadScheduledExecutor().schedule({
TODO("Do something")
}, 2, TimeUnit.SECONDS)
在Java中
1. 使用处理程序
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//Do something
}
}, 2000);
2. 使用定时器
new Timer().schedule(new TimerTask() {
@Override
public void run() {
// Do something
}
}, 2000);
3.使用ScheduledExecutorService
private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
Runnable runnable = new Runnable() {
public void run() {
// Do something
}
};
worker.schedule(runnable, 2, TimeUnit.SECONDS);
使用CountDownTimer非常简单。 详情https://developer.android.com/reference/android/os/CountDownTimer.html
import android.os.CountDownTimer;
// calls onTick every second, finishes after 3 seconds
new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
Log.d("log", millisUntilFinished / 1000);
}
public void onFinish() {
// called after count down is finished
}
}.start();
好吧,如果你使用Java,你总是可以使用遗留的Thread.sleep()。
new Thread(() -> {
try {
Thread.sleep(millis); //delay in milliseconds
} catch (Exception e) {
e.printStackTrace();
}
yourMethod();
}).start();
这里唯一的问题是你不能做任何UI更新,因为它是一个单独的线程。
低于1的情况下,
runtimeexception:不能在线程内部创建处理程序 没有调用loop .prepare()
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
}
}, 100);