我希望能够在指定的延迟后调用以下方法。 在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
}
当前回答
对于简单行句柄Post延迟,您可以执行以下操作:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// Do someting
}
}, 3000);
我希望这对你们有帮助
其他回答
如果你使用Android Studio 3.0及以上版本,你可以使用lambda表达式。callMyMethod()方法在2秒后被调用:
new Handler().postDelayed(() -> callMyMethod(), 2000);
如果你需要取消延迟的可运行文件,请使用以下命令:
Handler handler = new Handler();
handler.postDelayed(() -> callMyMethod(), 2000);
// When you need to cancel all your posted runnables just use:
handler.removeCallbacksAndMessages(null);
这里有另一个棘手的方法:当可运行的更改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));
动画可以附加到任何视图。
在我的例子中,我不能用其他答案。 我使用本机java定时器代替。
new Timer().schedule(new TimerTask() {
@Override
public void run() {
// this code will be executed after 2 seconds
}
}, 2000);
谢谢你的回答,我找到了一个最适合我需要的解决方案。
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
}
}
芬兰湾的科特林 从一个片段运行onuithread 计时器
例子:
Timer().schedule(500) {
activity?.runOnUiThread {
// code
}
}