2012-12-04 66 views

回答

1

您可以從對話框的取消事件中調用AsyncTask.cancel(true)。爲此,您需要對AsyncTask的引用,這可能是任務啓動時初始化的實例變量。然後在asyncTask.doInBackground()方法中,您可以檢查isCancelled(),或覆蓋onCancelled()方法並停止正在運行的任務。

例子:

//Asynctask instance variable 
private YourAsyncTask asyncTask; 

//Starting the asynctask 
public void startAsyncTask(){ 
    asyncTask = new YourAsyncTask(); 
    asyncTask.execute(); 
} 

//Dialog code 
loadingDialog = ProgressDialog.show(ThisActivity.this, 
               "", 
               "Loading. Please wait...", 
               false, 
               true, 
               new OnCancelListener() 
               { 

               @Override 
               public void onCancel(DialogInterface dialog) 
               { 
                if (asyncTask != null) 
                { 
                asyncTask.cancel(true); 
                } 
               } 
               }); 

編輯:如果您創建一個從裏面的AsyncTask的對話框,該代碼將不會有很大的不同。你可能不需要實例變量,我想你可以在這種情況下調用YourAsyncTask.this.cancel(true)。

1
I want to interrupt doInBackground when my custom cancel button pressed. 

=>呼籲取消按鈕點擊事件裏面你的AsyncTask的cancel()方法。現在,這不足以取消doInBackground()過程。

例如:

asyncTask.cancel(true); 

要通知您已使用cancel()方法取消的AsyncTask,你必須檢查其是否取消或不使用isCancelled()doInBackground()

例如:

protected Object doInBackground(Object... x) 
{ 
    // do your work... 

    if (isCancelled()) 
     break; 

}