2010-10-01 77 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本身内的超时。