当前位置: 代码迷 >> 综合 >> 线程 handler runnable 线程内结束
  详细解决方案

线程 handler runnable 线程内结束

热度:23   发布时间:2023-12-17 05:18:21.0

例如:新开线程,每5秒钟执行一边业务,当执行了10次,就停止线程

    val handler = Handler()//移除线程private val stopHandler: Handler = @SuppressLint("HandlerLeak")object : Handler() {override fun handleMessage(msg: Message) {when (msg.what) {1 -> {handler.removeCallbacks(runnable)}}super.handleMessage(msg)}}private var mThreadCount = 1//生成二维码成功之后开启线程val runnable = object : Runnable {override fun run() {mThreadCount += 1if (mThreadCount ==10) {//mThreadCount 等于10,就移除线程stayTimeOut()Log.e("------", "run 1111")}//执行一遍再次发送一遍事件,形成循环handler.postDelayed(this, mSleepTime)}}private fun stayTimeOut() {//在runnable线程内不能移除自己,需要通过新的handler发送消息移除//注意,要发送延迟消息!stopHandler.sendEmptyMessageDelayed(1,5000)}

//在这里开启线程

fun startThread(){ 

    handler.postDelayed(runnable , 1000)

}

 

override fun onDestroy() {super.onDestroy()//销毁活动,在主线程移除runnablehandler.removeCallbacks(runnable)
}override fun onPause() {super.onPause()//息屏或者进入下一个页面,在主线程移除runnablehandler.removeCallbacks(runnable) 
}

 

  相关解决方案