How do I cancel an AsyncTask
I am using an Asynctask as the loop controller for a game and noticed that the thread created kept on running after the activity was finished.
I realised that was the correct behavio开发者_运维问答ur of a separate thread and then I tried hunting down answers on how to end the thread when the app enters onPause.
I found lots of similar questions but no direct answers but eventually came up with a method so I'm going to answer my own question here to hopefully help others in future. (And to receive improvements to my answer as well)
Firstly, AsyncTask
have a fully valid cancel()
method. Secondly, do not use an AsyncTask
for a proper game loop. AsyncTask
isn't for long-running operations.
Therefore, skip AsyncTask
for your game loop and learn how to properly manage pausing / resuming in an ordinary Thread
by reading another answer from me here on SO.
public class CamOverlayTest extends Activity {
//...
public static BackgroundLoop BackgroundLoopTask;
//...
@Override
protected void onResume() {
//...
BackgroundLoopTask = new BackgroundLoop();
BackgroundLoopTask.execute();
}
@Override
protected void onPause() {
//...
BackgroundLoopTask.cancel(true);
}
private class BackgroundLoop extends AsyncTask<Void,Integer,Boolean> {
@Override
protected Boolean doInBackground(Void... arg0) {
int count =0;
while (!this.isCancelled()) {
// Basically, this is where the loop checks if the Aysnctask has been asked to be
// cancelled - if so - it exits.
try {
Thread.sleep(1000);
updatePhysics(count);
} catch (InterruptedException e) {
e.printStackTrace();
}
count +=1;
Log.i("SW","Count: "+count);
publishProgress();
}
return true;
}
@Override
protected void onProgressUpdate(Integer... values) {
// swDrawOnTop is my view
swDrawOnTop.invalidate();
}
//...
}
精彩评论