【问题标题】:Check if AsyncTask is taking too long检查 AsyncTask 是否耗时过长
【发布时间】:2013-03-06 14:21:24
【问题描述】:

我有一个从网络获取信息的 AsyncTask。有时连接失败,AsyncTask 进程对话框一直在运行。

在 doInBackground 中,我最后检查了我捕获的信息是否为空,如果是这种情况,它应该显示为正按钮/负按钮,但这没有发生。对话框正在运行。

如何检查 AsyncTask 是否花费了太长时间(可能是 5 秒)并关闭对话框?

代码 sn-p (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;
            }

提前致谢,如果您需要更多信息,请告诉我!

【问题讨论】:

  • 如果成功即订单!=null,您在哪里关闭对话框?
  • 在当前代码之上,因为当我在那里调用 publishProgress() 时我将其关闭。

标签: android


【解决方案1】:

您可以从进程中获取值并在onPostExecute() 中检查结果,而不是在doInBackground() 中检查结果,如下所示:

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 中编写上面的代码 sn-p 会破坏目的,对吗?我们希望用户不要等待超过 5 秒来等待来自 web 服务的回答,因此我们必须在 doInBackground 本身内处理超时。

    【讨论】:

      猜你喜欢
      • 2019-08-02
      • 2011-11-03
      • 2015-10-23
      • 2012-11-04
      • 2013-07-24
      • 2015-09-08
      • 2016-11-04
      • 2021-10-07
      相关资源
      最近更新 更多