4

私のアクティビティでは、複数の AsyncTask クラスを使用しています。

アクティビティが終了したときに AsyncTask をキャンセルするには?

4

3 に答える 3

7

これを行うのに最適な場所は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
    }
}
于 2012-12-13T11:40:48.333 に答える
2

「キャンセル」がロールバックを意味するかどうかはわかりませんが、 AsyncTaskクラスにcancelメソッドがあります。

于 2010-03-28T14:26:12.743 に答える
2

asynctask スレッドは、AsyncTask の将来のインスタンスのためにスレッド プール内で維持されます。それらを削除することはできません。

于 2011-10-17T08:12:00.533 に答える