How to stop asynctask thread in android?

2019-01-04 02:05发布

I want to stop a AsyncTask thread from another AsyncTask thread. I have tried like new AsyncTask.cancel(true) to stop the background process but it didn't stop.

Could any one help me on this?

6条回答
对你真心纯属浪费
2楼-- · 2019-01-04 02:22

You can't just kill asynctask immediately. In order it to stop you should first cancel it:

task.cancel(true);

and than in asynctask's doInBackground() method check if it's already cancelled:

isCancelled()

and if it is, stop executing it manually.

查看更多
淡お忘
3楼-- · 2019-01-04 02:23

u can check onCancelled() once then :

protected Object doInBackground(Object... x) {

while (/* condition */) {
  if (isCancelled()) break;
}
return null;

}

查看更多
你好瞎i
4楼-- · 2019-01-04 02:31

I had a similar problem - essentially I was getting a NPE in an async task after the user had destroyed the fragment. After researching the problem on Stack Overflow, I adopted the following solution:

volatile boolean running;

public void onActivityCreated (Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);

    running=true;
    ...
    }


public void onDestroy() {
    super.onDestroy();

    running=false;
    ...
}

Then, I check "if running" periodically in my async code. I have stress tested this and I am now unable to "break" my activity. This works perfectly and has the advantage of being simpler than some of the solutions I have seen on SO.

查看更多
看我几分像从前
5楼-- · 2019-01-04 02:35

declare your asyncTask in your activity:

private YourAsyncTask mTask;

instantiate it like this:

mTask = new YourAsyncTask().execute();

kill/cancel it like this:

mTask.cancel(true);
查看更多
萌系小妹纸
6楼-- · 2019-01-04 02:37

The reason why things aren't stopping for you is because the process (doInBackground()) runs until it is finished. Therefore you should check if the thread is cancelled or not before doing stuff:

if(!isCancelled()){
// Do your stuff
}

So basically, if the thread is not cancelled, do it, otherwise skip it :) Could be useful to check for this some times during your operation, especially before time taking stuff.

Also it could be useful to "clean up" alittle in

onCancelled();

Documentation for AsyncTask:

http://developer.android.com/reference/android/os/AsyncTask.html

Hope this helps!

查看更多
Ridiculous、
7楼-- · 2019-01-04 02:38

You may also have to use it in onPause or onDestroy of Activity Life Cycle:

//you may call the cancel() method but if it is not handled in doInBackground() method
if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED)
    loginTask.cancel(true);

where loginTask is object of your AsyncTask

Thank you.

查看更多
登录 后发表回答