我希望能够在指定的延迟后调用以下方法。 在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
}
当前回答
使用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();
其他回答
有很多方法可以做到这一点,但最好的是使用如下处理程序
long millisecDelay=3000
Handler().postDelayed({
// do your work here
},millisecDelay)
这里有另一个棘手的方法:当可运行的更改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));
动画可以附加到任何视图。
使用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();
我更喜欢使用View.postDelayed()方法,下面是简单的代码:
mView.postDelayed(new Runnable() {
@Override
public void run() {
// Do something after 1000 ms
}
}, 1000);
更安全-与Kotlin协程
大多数答案使用Handler,但我给出了一个不同的解决方案来延迟活动,片段,视图模型与Android Lifecycle ext.这种方式将自动取消生命周期开始破坏-避免泄漏内存或崩溃的应用程序
在活动或片段中:
lifecycleScope.launch {
delay(DELAY_MS)
doSomething()
}
在ViewModel:
viewModelScope.lanch {
delay(DELAY_MS)
doSomething()
}
在挂起函数:(Kotlin协程)
suspend fun doSomethingAfter(){
delay(DELAY_MS)
doSomething()
}
如果您得到一个错误,lifecycleScope没有找到!-将这个依赖导入到应用的gradle文件中:
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.4.0"