2010-10-01 78 views
2

我有一個從網絡中信息的的AsyncTask。有時候連接失敗,AsyncTask進程對話框會一直運行。檢查的AsyncTask的時間太長

在doInBackground我有一查到底,如果我逮住信息是空的,如果是這樣的話,它應該出現清晰的按鍵/負號按鈕,但這沒有發生。對話框正在運行。

我如何檢查是否一個的AsyncTask花費太長時間(也許5秒),並關閉該對話框?

代碼段(doInBackground):提前

//orders is my ArrayList<Order> object, from my own Order class. 
if(orders==null) { 
       pdia.dismiss(); 
       AlertDialog.Builder alt_bld = new AlertDialog.Builder(ctx); 
       alt_bld.setMessage("Try agin?") 
       .setCancelable(false) 
       .setPositiveButton("Try again", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 

        button_refresh.setVisibility(View.GONE); 

        new ListTask().execute(null, null , null); 


       } 
       }) 
       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
       dialog.cancel(); 
       } 

       }); 
       AlertDialog alert = alt_bld.create(); 
       alert.setTitle("Connection failed!"); 
       alert.show(); 
      } 
      else { 
       return orders; 
      } 

感謝,並告訴我,如果你需要更多的信息!

+0

在成功的情況下,你在哪裏解僱對話,即命令!= null? – bhups 2010-10-01 08:38:12

+0

當前代碼上方,因爲當我打電話給publishProgress()時,我忽略它。 – Curtain 2010-10-01 09:19:55

回答

2

而不是檢查你的結果doInBackground()你可以從過程中獲得的價值,並檢查它在onPostExecute(),像這樣的:

protected void onPostExecute(ArrayList<Order> localOrders){ 
    super.onPostExecute(localOrders); 
    if (localOrders==null) { 
     // Paste the positive and negative DialogListeners here 
     // and dismiss the dialog. 
    } 
} 

結果doInBackground()過程轉移到onPostExecute的參數,因此你可以檢查你的ArrayList對象是否爲空。

2

但隨後寫在onPostExecute上面的代碼片斷將擊敗的目的吧?我們希望用戶不要等待5秒鐘以等待web服務的響應,因此我們必須處理doInBackground本身內的超時。