package com.duolebo.blyrobot.tools import android.util.Log import com.duolebo.blyrobot.data.Task import kotlin.collections.ArrayList class TaskManager { private val TAG = "TaskManager" val tasks = ArrayList() private var isRunning = false private var currentTask: Task ?= null // 处理时间 var updateTime = 0L private val runnable = Runnable { val dist = System.currentTimeMillis() - updateTime while (isRunning && tasks.size > 0 && dist > 6*60*60*1000) { this.updateTime = System.currentTimeMillis() currentTask = tasks[0] currentTask!!.start() } } fun add(task: Task) { task.taskListener = object : Task.OnTaskListener { override fun onComplete(result: Boolean) { Log.i(TAG, "task ${task.apkInfo.name} complete with result: $result") } } this.tasks.add(task) } fun remove(task: Task) { val item = tasks.find { it.apkInfo.packageName == task.apkInfo.packageName } item?.run { tasks.remove(this) } } fun isExist(task: Task): Boolean { val item = tasks.find { it.apkInfo.packageName == task.apkInfo.packageName } return item != null } fun start() { if (this.isRunning) { Log.i(TAG, "is running") return } if (this.tasks.size <= 0) { Log.i(TAG, "no tasks") return } this.isRunning = true val t = Thread(runnable) t.start() } fun stop() { updateTime = 0L this.tasks.forEach { it.destroy() } this.tasks.clear() this.isRunning = false } companion object { val instance = TaskManager() } }