0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Androidで、カウントダウンを

Posted at

Androidで、カウントダウンを実装しようと思ったのですが、CountDownTimerが微妙な感じで、代わりになるものがないか検討したので、記事にしたいと思います。

結論

postDelayedで、実装することにしました。
ポイントとしては、postDelayedにthisを渡して、runnableを繰り返すことでカウントダウン出来ます。

    private var selfTimerCount = 10
    private val handler = Handler(Looper.getMainLooper())
    private val runnable = object : Runnable {
        override fun run() {
            if (selfTimerCount == 0) {
                // 何かを実行する
                return
            }
            selfTimerCount--
            handler.postDelayed(this, TIMER)
        }
    }

    override fun onResume() {
        super.onResume()

        handler.post(runnable)
    }

    override fun onPause() {
        super.onPause()

        handler.removeCallbacks(runnable)
    }
    
    companion object {
        private const val TIMER = 1000L
    }    
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?