目标

在kotlin中使用Timer执行定时任务.

解决方案
class MainActivity : AppCompatActivity() {
    lateinit var timer: Timer

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        startBtn.setOnClickListener { startTimer() }
        stopBtn.setOnClickListener { stopTimer() }
    }

    private fun startTimer() {
        timer = fixedRateTimer("", false, 0, 1000) {
            toast("得瑟中。。。")
            Log.d("MainActivity", "得瑟中。。。")
        }
    }

    private fun stopTimer() {
        timer.cancel()
        toast("醒醒!!!")
        Log.d("MainActivity", "醒醒!!!")
    }

    private fun toast(text: String) {
        runOnUiThread {
            Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
        }
    }
}
源代码

https://gitee.com/hspbc/TimerDemo

关于我

厦门大学计算机专业 | 前华为工程师
分享编程技术,没啥深度,但看得懂,适合初学者。
Java | 安卓 | 前端 | 小程序 | 鸿蒙
公众号:花生皮编程
​​​​​​​Kotlin中使用Timer_ide