【问题标题】:Async Task Error Handling [duplicate]异步任务错误处理 [重复]
【发布时间】:2012-02-07 20:11:40
【问题描述】:

我正在编写一个流直播广播的 Android 应用程序。我已经设置了一个异步任务来在流加载时显示一个进度对话框。这工作正常,但是当它遇到“关闭”且无法运行的流时,我的应用程序崩溃,我只想知道处理错误的最佳方法。

代码如下:

public class loadingData extends AsyncTask<Object, Object, Object>{


    protected void onPreExecute() {

        progDialog = new ProgressDialog(radioplayer.this);
            progDialog.setMessage("Loading radio station");
            progDialog.setIndeterminate(true);
            progDialog.setCancelable(false);
            progDialog.show();

    }   
    protected Object doInBackground(Object... arg0) {

        prs.setStation(strStation);        
        return null;
    }   
    protected void onCancelled() {

        super.onCancelled();
    }
    protected void onPostExecute(Object result) {

        progDialog.hide();
    }
    protected void onProgressUpdate(Object... values) {     
    }   
}

【问题讨论】:

    标签: android


    【解决方案1】:

    this 的副本

    如果您使用 Roboguice,则有一种内置方式可以处理异步任务中的异常。

    【讨论】:

      【解决方案2】:

      你可以做的(我在我的应用程序中使用这个技巧)是这样的:

      protected Object doInBackground(Object... arg0) {
          try {
              prs.setStation(strStation);
              return null;
          }
          catch(Exception ex)
          {
              return ex;
          }
      }
      
      
      protected void onPostExecute(Object result) {
          progDialog.hide();         
          if(result != null && result instanceof Exception) {
              String errText = ((Exception)result).getMessage();
              //now deal with your exception on the UI thread
          }
      }
      

      【讨论】:

      • -1 我认为这很难看,尤其是 Object 返回类型。如果必须结合异常处理和返回值,至少将函数返回声明为异常。但即便如此,返回 null 或异常的想法似乎很糟糕。
      • 感谢您解释“-1”。在我的代码中,我不返回Object 类型,而是返回String,它要么是null,要么包含错误消息。它符合我的目的。我保留了Object 返回类型,因为它是由提问者给出的。
      • Aleks 谢谢,谢谢,谢谢!!它就像一种魅力,为我节省了很多时间。干杯。
      猜你喜欢
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多