繁体   English   中英

如何设置一个计时器,该计时器在活动中完成后会执行某些操作(如果单击该按钮会发生其他事情)?

[英]How to set a timer that do something after it finishes in an activity with button that if clicked something else happens?

我的Android应用程式中有个活动,向使用者显示字词。 如果用户可以在不到60秒的时间内猜出答案,则可以按下按钮并进入另一项活动。 但是如果他做不到并且时间还没结束,则必须显示第三项活动。 我该怎么办? 与线程或计时器或类似的东西?

我尝试了线程处理,但应用程序崩溃了。

您可以通过使用处理程序来实现。

科特林

// declare this variables as attributes in you class
val handler = Handler()
val runnable = Runnable {
    // Call something when it finishes
}
handler.postDelayed(runnable, 60_000) // Do something after 60 seconds


// and if you want to cancel the timer, you can cancel it this way
handler.removeCallbacks(runnable)

Java的

// declare this variables as attributes in you class
Handler handler = new Handler();
Runnable runnable = new Runnable() {
    public void run() {
        // Call something when it finishes
    }
};
handler.postDelayed(runnable, 60_000);

// and if you want to cancel the timer, you can cancel it this way
handler.removeCallbacks(runnable);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM