如何在Activity完成时取消AsyncTask?

Pen*_*m10 4 multithreading android android-asynctask android-activity

在我的Activity中,我使用了多个AsyncTask类.

如何在Activity完成时取消AsyncTask?

mar*_*itz 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的任务中,我会尽可能经常检查取消是否被调用

protected String doInBackground(String... arg0) {
    if (this.isCancelled()) {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

当然不要忘记丢弃可能返回的数据,因为没有更多的Activity可以接收它

protected void onPostExecute(List<UserStatus> result) {
    if(!this.isCancelled()) {
        //pass data to receiver
    }
}
Run Code Online (Sandbox Code Playgroud)