我希望能够在指定的延迟后调用以下方法。 在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
}
当前回答
这里有另一个棘手的方法:当可运行的更改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,但我给出了一个不同的解决方案来延迟活动,片段,视图模型与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"
每个人似乎都忘记在发布新的可运行文件或消息之前清理处理程序。否则,它们可能会累积并导致不良行为。
handler.removeMessages(int what);
// Remove any pending posts of messages with code 'what' that are in the message queue.
handler.removeCallbacks(Runnable r)
// Remove any pending posts of Runnable r that are in the message queue.
科特林
Handler(Looper.getMainLooper()).postDelayed({
//Do something after 100ms
}, 100)
Java
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
}
}, 100);
要导入的类是android.os.handler。
在Android中,我们可以编写下面的kotlin代码来延迟任何函数的执行
class MainActivity : AppCompatActivity() {
private lateinit var handler: Handler
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
handler= Handler()
handler.postDelayed({
doSomething()
},2000)
}
private fun doSomething() {
Toast.makeText(this,"Hi! I am Toast Message",Toast.LENGTH_SHORT).show()
}
}
final Handler handler = new Handler();
Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
//DO SOME ACTIONS HERE , THIS ACTIONS WILL WILL EXECUTE AFTER 5 SECONDS...
}
});
}
}, 5000);