【问题标题】:Kill Runnable process杀死 Runnable 进程
【发布时间】:2019-03-04 14:49:18
【问题描述】:

我有一个简单的计时器功能。该函数在 OnCreate() 中调用。 当我去另一个活动并回来时,我的带计时器的活动被重新创建,计时器开始工作的速度提高了 2 倍。

我试图从我的 Runnable 中删除 removeCallbacks,但它不起作用。

如何杀死我的 Runnable 以防止堆叠。

private fun onTimerStart(){
        ed.putBoolean("thread", true).apply()
        mRunnable = Runnable {
            seconds = sp.getLong("SECONDS",0)
            try {
                if (seconds!=0L){
                    startRun = true
                    btnStartEnd.text = getString(R.string.stop)
                }
            }catch (ex:Exception){}
            val hours = seconds/3600
            val minutes = (seconds%3600)/60
            val secs = (seconds%60)
            val time = String.format("%d:%02d:%02d", hours, minutes, secs)
            txtClock.text = time
            if (startRun){
                seconds++
                ed.putLong("SECONDS",seconds).apply()
            }
            mHandler.postDelayed(this,1000)
        }
        mHandler.postDelayed(mRunnable,1000)
    }

【问题讨论】:

    标签: android kotlin runnable


    【解决方案1】:

    你的 Runnable 没有被杀死,因为它在删除后在处理程序中运行。

    var mIsStopped = false
    
    private fun onTimerStart() {
        ed.putBoolean("thread", true).apply()
        mRunnable = Runnable {
            seconds = sp.getLong("SECONDS", 0)
            try {
                if (seconds != 0L) {
                    startRun = true
                    btnStartEnd.text = getString(R.string.stop)
                }
            } catch (ex: Exception) {
            }
            val hours = seconds / 3600
            val minutes = (seconds % 3600) / 60
            val secs = (seconds % 60)
            val time = String.format("%d:%02d:%02d", hours, minutes, secs)
            txtClock.text = time
            if (startRun) {
                seconds++
                ed.putLong("SECONDS", seconds).apply()
            }
            if (!mIsStopped) mHandler.postDelayed(this, 1000)
        }
        mHandler.postDelayed(mRunnable, 1000)
    }
    
    override fun onPause() {
        mHandler.removeCallbacksAndMessages(null);
        mIsStopped = true
    }
    
    override fun onResume() {
        mIsStopped = false
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-08
      • 1970-01-01
      • 2013-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-31
      相关资源
      最近更新 更多