2011-09-06 4 views
0

나는 다음과 같은 코드가 있습니다안드로이드 AsyncTask를 - onPostExecute 호출되지 않습니다 (해서 ProgressDialog)

try { 
    res = new Utils(ubc_context).new DownloadCalendarTask().execute().get(); 
} catch (InterruptedException e) { 
    Log.v("downloadcalendar", "interruptedexecution : " + e.getLocalizedMessage()); 
    res = false; 
} catch (ExecutionException e) { 
    Log.v("downloadcalendar", "executionexception : " + e.getLocalizedMessage()); 
    res = false; 
} 

Log.v("displaymenu", "A"); 

public class Utils { 

private Context context; 

public Utils(Context context) { 
    this.context = context; 
} 

public class DownloadCalendarTask extends AsyncTask<Void, Void, Boolean> { 

    private ProgressDialog dialog; 

    public DownloadCalendarTask() { 

    dialog = new ProgressDialog(context); 

    } 

    protected void onPreExecute() { 
     Log.v("preexecute", "A"); 
     dialog.setMessage("Loading calendar, please wait..."); 
     Log.v("preexecute", "B"); 
     dialog.show(); 
     Log.v("preexecute", "C"); 

    } 

    protected Boolean doInBackground(Void... arg0) { 
     // do some work here... 
     return (Boolean) false; 
    } 

    protected void onPostExecute() { 
     Log.d("utils", "entered onpostexecute"); 
     dialog.dismiss(); 
    } 

} 
} 

코드의 첫 번째 부분은 버튼에 대한 onClick 수신기에 연결되어 있습니다. 단추를 클릭하면 버튼이 깜박이며 (클릭 한 것처럼 표시됨) 약 8 초 후로드 대화 상자가 나타나지만 끝나지 않습니다.

logcat에 따르면 onPreExecute이 실행되면 Dialog.show()처럼 실행되므로 내 첫 번째 문제는 왜이 8 초 지연입니까? 이 8 초 동안 logcat은 doInBackground이 실행 중임을 보여줍니다. 그러나 logcat에 따르면 (이 문제는 두 번째 임) onPostExecute는 결코 호출되지 않습니다. 따라서 Dialog.dismiss()가 실행되지 않습니다.

Logcat은 DownloadCalendarTask().execute().get() 다음의 모든 항목이 실행되고 있음을 보여주기 때문에 마치 onPostExecute이 건너 뛴 것처럼 보입니다.

많은 도움을 주셔서 감사합니다.

답변

1

AsyncTask.get()을 호출하면 AsyncTask가 실행되는 동안 UI 스레드가 차단됩니다.

new DownloadCalendarTask().execute().get(); 

get() 호출을 제거하면 비동기 적으로 수행되고 예상되는 결과가 제공됩니다.

new DownloadCalendarTask().execute(); 

편집 : 당신은 또한 당신의 onPostExecute 메서드에 매개 변수를 갱신해야합니다, 그들은 결과를 포함해야합니다. 예 :

protected void onPostExecute(Boolean result) { 
+0

감사합니다. 하지만 get()을 제거하면 AysncTask의 결과를 검색하는 쉬운 방법이 있습니까? – Jonny

+0

결과를 가져 오는 가장 간단한 방법은 AsyncTask를 Activity의 내부 클래스로 만든 다음 onPostExecute 메서드에서 Activity의 메서드를 호출하여 해당 작업에 결과를 전달하는 것입니다. – Rob

+0

이 변경 작업을 수행하고 ProgressDialog가 곧바로 표시되지만 이제 doInBackgroundAction의 코드가 실행되고 return 문 끝까지 도달하지만 아무 것도하지 않는 것으로 보입니다. 그러면 progressdialog가 끝나지 않습니다. 다시, onPostExecute는 결코 호출되지 않습니다. – Jonny

관련 문제