私のアクティビティでは、複数の AsyncTask クラスを使用しています。
アクティビティが終了したときに AsyncTask をキャンセルするには?
私のアクティビティでは、複数の AsyncTask クラスを使用しています。
アクティビティが終了したときに AsyncTask をキャンセルするには?
これを行うのに最適な場所はonStop
protected void onStop() {
super.onStop();
/*
* The device may have been rotated and the activity is going to be destroyed
* you always should be prepared to cancel your AsnycTasks before the Activity
* which created them is going to be destroyed.
* And dont rely on mayInteruptIfRunning
*/
if (this.loaderTask != null) {
this.loaderTask.cancel(false);
}
}
私のタスクでは、キャンセルが呼び出されたかどうかをできるだけ頻繁に確認します
protected String doInBackground(String... arg0) {
if (this.isCancelled()) {
return null;
}
}
もちろん、返される可能性のあるデータをドロップすることを忘れないでください。それを受け取るアクティビティがこれ以上ないためです。
protected void onPostExecute(List<UserStatus> result) {
if(!this.isCancelled()) {
//pass data to receiver
}
}
asynctask スレッドは、AsyncTask の将来のインスタンスのためにスレッド プール内で維持されます。それらを削除することはできません。