开发者

Need to kill one task if other is started

I have a code which is running asynchronously and it is call开发者_运维问答ed from the main thread. It can be called by main thread multiple number of times. I want to finish the earlier execution of the asynchronous task to be destroyed as soon as I start a new instance of it through main thread.

I tried it using cancel of AsyncTask in java. But calcel works only after doInBackground(params..). So this doesn't work

Can it be achieved in some way? I also tried putting this asyncronous task in thread. But don't know how to cancel the operation started by thread.


In your thread declare a boolean running. Then wrap the execution of doInBackground & onPostExecute in a while running statement. Keep a reference to the asynctask, if not null, set running to false, which should kill the old task. Then create a new one.

*Edit: by kill the old task, I mean cause it to complete early


So here goes:

  • you need to declare one class member of that type of task : private MyTask mMyTask
  • in your doInBackground() method you will have to check from time to time if the task was canceled. If you have a for loop you will mostly do it in this way for(int i=0;i<0;!isCancelled();i++) or in a while loop while(myCondition && !isCancelled()){...}
  • when you want to cancel your task do the following :mMyTask.cancel(); mMyTask=new MyTask(); mMyTask.execute();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜