Android 如何为新任务取消旧任务
我试图使用AsyncTask在用户触摸屏幕时从数据库中提取数据。每次用户触摸应用程序上的屏幕时,都会创建一个新任务。我想要的是,每当用户触摸屏幕时,无论该任务是否已完成工作,都要停止并销毁旧任务,并替换为新任务 这是在应用程序上下文中完成的,至少在存储库所在的上下文中是这样。 我已经制作了几个控制结构,以使其取消先前的异步任务,但似乎都不起作用Android 如何为新任务取消旧任务,android,kotlin,android-asynctask,Android,Kotlin,Android Asynctask,我试图使用AsyncTask在用户触摸屏幕时从数据库中提取数据。每次用户触摸应用程序上的屏幕时,都会创建一个新任务。我想要的是,每当用户触摸屏幕时,无论该任务是否已完成工作,都要停止并销毁旧任务,并替换为新任务 这是在应用程序上下文中完成的,至少在存储库所在的上下文中是这样。 我已经制作了几个控制结构,以使其取消先前的异步任务,但似乎都不起作用 var getBoundedMomentsTask : BoundsRequestTask = BoundsRequestTask() //Start
var getBoundedMomentsTask : BoundsRequestTask = BoundsRequestTask()
//Starts an asynchronous task
//Called by ViewModel
//A list of moments is returned to the live data object
fun queryMapMoments(bounds : LatLngBounds, zoom : Float ) {
//If the request is already running, end it
if (getBoundedMomentsTask.status == AsyncTask.Status.RUNNING) {
getBoundedMomentsTask.cancel(true)
}
//The while loop just hung up the system.
//while (getBoundedMomentsTask.status == AsyncTask.Status.RUNNING) {
// getBoundedMomentsTask.cancel(true)
//}
//Begin the new task
getBoundedMomentsTask.execute(BoundsTaskParams(bounds, zoom))
}
inner class BoundsRequestTask : AsyncTask<BoundsTaskParams, Void, List<Moment>>() {
override fun doInBackground(vararg params: BoundsTaskParams?): List<Moment> {
val bounds: LatLngBounds? = params[0]?.bounds
val zoom: Float? = params[0]?.zoom
if (!isCancelled) {
Log.d("doInBackground", "Getting map channel")
val channel = checkMapChannels(bounds, zoom)
if (!isCancelled) {
Log.d("doInBackground", "Asking for moments from database")
channel.fetchDatabaseMoments()
} else {
return mutableListOf()
}
if (!channel.networkRequested) {
if (!isCancelled) {
Log.d("doInBackground", "Asking for moments from network")
channel.fetchMomentsOnNetwork()
} else {
return mutableListOf()
}
}
//Save the channel and return the moments
Log.d("doInBackground", "Saving the returned channel")
channels.add(channel)
return channel.regionMoments
} else {
return mutableListOf()
}
}
override fun onPostExecute(list : List<Moment>) {
mappedMoments.value = list
}
}
我得到的错误是无法执行任务:任务已经执行。任务只能在具有的行上执行一次
getBoundedMomentsTask.ExecuteBoundStataskParamsBounds,zoom您必须创建一个新的任务实例。单个实例只能执行一次。对其调用cancel,并在doInBackground中每隔一段时间取消一次原始检查,如果为true,则停止。