我希望能够在指定的延迟后调用以下方法。 在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
}
当前回答
低于1的情况下,
runtimeexception:不能在线程内部创建处理程序 没有调用loop .prepare()
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
}
}, 100);
其他回答
谢谢你的回答,我找到了一个最适合我需要的解决方案。
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
}
}
这里有另一个棘手的方法:当可运行的更改UI元素时,它不会抛出异常。
public class SimpleDelayAnimation extends Animation implements Animation.AnimationListener {
Runnable callBack;
public SimpleDelayAnimation(Runnable runnable, int delayTimeMilli) {
setDuration(delayTimeMilli);
callBack = runnable;
setAnimationListener(this);
}
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
callBack.run();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
}
你可以像这样调用动画:
view.startAnimation(new SimpleDelayAnimation(delayRunnable, 500));
动画可以附加到任何视图。
下面是Kotlin的答案,你们这些懒惰的人:
Handler().postDelayed({
//doSomethingHere()
}, 1000)
注意:这个答案是在问题没有指定Android作为上下文时给出的。对于特定于Android UI线程的答案,请查看这里。
看起来Mac OS API允许当前线程继续运行,并安排任务异步运行。在Java中,等价的函数由Java .util.concurrent包提供。我不确定Android会有什么限制。
private static final ScheduledExecutorService worker =
Executors.newSingleThreadScheduledExecutor();
void someMethod() {
⋮
Runnable task = new Runnable() {
public void run() {
/* Do something… */
}
};
worker.schedule(task, 5, TimeUnit.SECONDS);
⋮
}
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);