重试AsyncTask

时间:2011-03-17 08:17:42

标签: android

例如,我有以下AsyncTask:

  private class MyAsyncTask extends AsyncTask<Void, Void, Boolean> {


     @Override
     protected Void doInBackground(Void... params) {
         try {
             //some code that may throws exception
             return true;
         } catch (IOException ex) {
             return false;
         }
     }


     @Override
     protected void onPostExecute(Boolean param){
        if (!param) {
           AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
           builder.setMessage("Error");
           builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
                  //I want to retry MyAsyncTask here
              } 
           });
           builder.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
                 finish();
              } 
           });
           AlertDialog alert = builder.create();
           alert.show();
        }
     }
  }

这样做的最佳做法是什么?我害怕递归此代码。

4 个答案:

答案 0 :(得分:7)

您无法严格“重试”AsyncTask的实例。您必须创建一个新实例并执行它,就像您执行第一个实例一样。你不应该遇到递归问题。

答案 1 :(得分:2)

我在doInBackground()内重试代码x次:

 @Override
 protected Void doInBackground(Void... params)
 {
    final int MAX_RETRY=3;
    int iLoop;
    boolean bSuccess=true;
    for (iLoop=0; iLoop<MAX_RETRY; iLoop++)
    {
        try
        {
            //do some code that throw an exception

            //success! exit loop
            iLoop=0;
            break;
        }
        catch (IOException ex)
        {
            bSuccess=false;
        }
    }
    if (iLoop==(MAX_RETRY-1))
    {
        bSuccess=false;
    }
    return bSuccess;
 }

这也是布尔值的两个值不足以衡量成功的时候之一。您可以使用枚举替换bSuccess以获得第三个成功度:稍后重试。

答案 2 :(得分:1)

我使用BetterASyncTask解决了同样的问题。

它提供了方便的HandleError抽象方法,它允许我在UI线程上捕获异常并决定是否重试以及如何重试。

答案 3 :(得分:0)

请查看retryableasynctask并查看是否有帮助。

用法:

// Params, Progress and Result could be anything, same as a regular AsyncTask
new RetryableAsyncTask<Params, Progress, Result>(myActivity) {
  @Override
  protected void onPreExecute() {
    // write some code here
  }

  @Override
  protected Result doInBackground(Params... params) {
    // execute some expensive task here with your params
    // eg: MyExpensiveTask with method called 'get'

    return MyExpensiveTask.get(params);
  }

  @Override
  protected void onPostExecute(Result result) {
    // write some code here with your result
  }
}.execute(myParams);

覆盖“onError”行为

默认情况下,onError方法会显示一个对话框“取消”和“重试”按钮选项。但是,当出现问题时,您可能想要做其他事情。为此,请使用您自己的错误处理覆盖onError。

// Params, Progress and Result could be anything, same as a regular AsyncTask  
new RetryableAsyncTask<Params, Progress, Result>(myActivity) {
  // ...

  @Override
  protected void onError(Throwable error, final Params... params) {
    // write your own error handling
  }
}.execute(myParams);