我希望能够在指定的延迟后调用以下方法。 在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
}
当前回答
好吧,如果你使用Java,你总是可以使用遗留的Thread.sleep()。
new Thread(() -> {
try {
Thread.sleep(millis); //delay in milliseconds
} catch (Exception e) {
e.printStackTrace();
}
yourMethod();
}).start();
这里唯一的问题是你不能做任何UI更新,因为它是一个单独的线程。
其他回答
5秒后在UI线程中执行一些东西:
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
//Do something here
}
}, 5000);
android中合适的解决方案:
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
}
}
如果你使用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);
对活动类的另一个响应(java8)。
//hide with delay
new Thread(() -> {
try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}
this.runOnUiThread(() -> {
myView.setVisibility(View.GONE);//this run on GUI
});
}).start();
更安全-与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"