Kotlin writes a tool class that executes periodically

insert image description here

1. Define the interface

In order to put the cyclically executed tasks outside the tool class, an interface is defined to implement the interface callback. Secondly, in order to make the interface callback more concise, the java language is used to define the interface here (kotlin is suspected to be not so easy to use)

public interface ActionCallback<T,V> {
    
    
    void actionDo(T TAG,V VALUE);
}

Second, the timer for loop execution

import android.util.Log
import java.util.*
import kotlin.concurrent.schedule

/**
 * 循环执行发送操作
 * @auther 绝命三郎
 */
class CycleSender {
    
    

    private var timer:Timer=Timer()
    private var runningTag=false
    companion object {
    
    
        val INSTANCE by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
    
    
            CycleSender()
        }
    }

    //启动循环
    fun start(callback : ActionCallback<String,String>){
    
    
        if (!runningTag){
    
    
            runningTag=true
            timer=Timer()
            timer.schedule(0, 100) {
    
    
                callback.actionDo("TAG","VALUE")
            }
        }
    }

    //暂停循环
    fun stop(){
    
    
        if (runningTag) {
    
    
            runningTag=false
            timer.cancel()
        }
    }
}

3. How to use

//周期循环请求0x100数据
CycleSender.INSTANCE.start(ActionCallback {
    
     tag, value ->
    //执行周期循环的任务
})

Guess you like

Origin blog.csdn.net/qq_41008818/article/details/129881043