2012-12-04 5 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); 

당신이() 메소드를 취소하여 AsyncTask를 취소 한 것으로 알려하려면, 당신은 그 취소 또는 doInBackground() 내부 isCancelled()를 사용하지 여부를 확인해야합니다. 예를 들어

:

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

    if (isCancelled()) 
     break; 

} 
관련 문제