アクティビティの終了時に AsyncTask をキャンセルするにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/2533149

質問

私のアクティビティでは、複数の 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の将来のインスタンスのためのスレッド・プールに生かされています。あなたはそれらを削除することはできません。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top