我执行了以下函数,每15秒生成一个处理程序事件。它以给定标志开始,当我传递False时,我希望处理程序停止其循环。这是我在Kotlin中的代码段:
private fun getSalesData(session:Boolean,delayMs:Long,salesRequest: JsonObjectRequest){
lateinit var runnable: Runnable
if (session) {
HttpRequestSingleton.getInstance(this@NavBarActivity).addToRequestQueue(salesRequest)
}
Handler().apply {
runnable = object : Runnable {
override fun run() {
HttpRequestSingleton.getInstance(this@NavBarActivity).addToRequestQueue(salesRequest)
Log.d(TAG, "se esta repitiendo cada 15 segs mamahuevo")
postDelayed(this, delayMs)
}
}
postDelayed(runnable, delayMs)
if (!session){
Log.d(TAG,"entre aca como todo un crack")
Handler().removeCallbacksAndMessages(runnable)
}
}
if(!session){
Log.d(TAG,"aanopqwwwwww")
Handler().removeCallbacksAndMessages(runnable)
}
}
答案 0 :(得分:0)
要确切地了解您想做什么有点困难,但这是可行的解决方案:
private fun getSalesData(session:Boolean,delayMs:Long,salesRequest: JsonObjectRequest){
lateinit var runnable: Runnable
if (session) {
HttpRequestSingleton.getInstance(this@NavBarActivity).addToRequestQueue(salesRequest)
}
Handler().apply {
runnable = object : Runnable {
override fun run() {
HttpRequestSingleton.getInstance(this@NavBarActivity).addToRequestQueue(salesRequest)
Log.d(TAG, "se esta repitiendo cada 15 segs mamahuevo")
postDelayed(this, delayMs)
}
}
postDelayed(runnable, delayMs)
if (!session){
Log.d(TAG,"entre aca como todo un crack")
removeCallbacks(runnable) // just call this method, as part of your handler object
}
}
if(!session){
Log.d(TAG,"aanopqwwwwww")
removeCallbacks(runnable)// just call this method, as part of your handler object
}
}
更新:对不起,没有看到您使用了removeCallbacksAndMessages
。 removeCallbacks
将删除所有排队的可运行对象