简体   繁体   中英

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

I have an activity in my android app that shows a word to the user. if the user could guess the answer in less than 60 seconds he would press a button and go to another activity. but if he could not do it and the time finishes, a third activity must show. How should I do it? with threading or timer or something like that?

I have tried threading but the app crashes.

You can achieve this by using Handler.

Kotlin

// 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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