Maf*_*aff 1 android kotlin android-studio
我有一个倒计时 60 秒的活动,但是,如果用户导航离开该活动,无论是使用屏幕上的后退按钮还是按下 Android 后退按钮,我都需要取消倒数计时器,否则它只会继续背景。这是我必须启动计时器的代码:
import android.os.CountDownTimer
class GamePlay : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// play music, though it's cutting out after 15 seconds for some reason
var musicPlayer: MediaPlayer? = MediaPlayer.create(this, R.raw.backgroundmusic)
musicPlayer?.start()
// start the timer
object : CountDownTimer(60000, 1000) {
override fun onFinish() {
val intent = Intent(applicationContext,Results::class.java)
startActivity(intent)
}
override fun onTick(p0: Long) {
time.text = ""+p0/1000
}
}.start()
}
}
// function for clicking the back button on screen
fun goToMainMenu(view:View){
val intent = Intent(applicationContext,MainMenu::class.java)
startActivity(intent)
}
Run Code Online (Sandbox Code Playgroud)
我原以为会是这样,CountDownTime.cancel()但我不知道该怎么做,而且如果用户使用系统后退按钮,我也不知道如何让它做到这一点。
任何指针表示赞赏。
只需将 CountDownTimer 设置为 val 并调用 val.cancel()
创造财产
private lateinit var timer: CountDownTimer
Run Code Online (Sandbox Code Playgroud)
将 val 设置为 CountDownTimer
timer = object : CountDownTimer(60000, 1000) {
override fun onFinish() {
val intent = Intent(applicationContext,Results::class.java)
startActivity(intent)
}
override fun onTick(p0: Long) {
time.text = ""+p0/1000
}
}.start()
Run Code Online (Sandbox Code Playgroud)
在 backpress 函数上设置 timer.cancel()
override fun onBackPressed() {
super.onBackPressed()
timer.cancel()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1613 次 |
| 最近记录: |