异步任务失败时向用户提供反馈

时间:2014-02-19 20:57:59

标签: java android android-asynctask

我使用AsyncTask发送电子邮件:

class AsyncSendEmail extends AsyncTask<String, Void, String> {

private Exception exception;
Session session;

public AsyncSendEmail(Session _session)
{
    session = _session;
}

protected String doInBackground(String... parms) {
    try {

            MimeMessage message = new MimeMessage(session);   
            DataHandler handler = new DataHandler(new ByteArrayDataSource(parms[1].getBytes(), "text/plain"));   
            message.setSender(new InternetAddress(parms[2]));   
            message.setSubject(parms[0]);   
            message.setDataHandler(handler);   
            if (parms[2].indexOf(',') > 0)   
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(parms[2]));   
            else  
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(parms[2]));   
            Transport.send(message);  
            return "SUC";
    } catch (Exception e) {
        e.printStackTrace();
        return "FLD";
    }
}

方法调用:

public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception 
{   
    new AsyncSendEmail(session).execute(subject,body,sender,recipients);
}   

当我的“doInBackground”方法出现问题时,我希望使用通知提醒用户。

我该怎么做?如何从方法调用中捕获异常?

或者我如何获得上下文以便我可以显示通知?

3 个答案:

答案 0 :(得分:0)

在AsyncTask中:

private Exception lastException = null;

protected String doInBackground(String... parms) {
    try {

        MimeMessage message = new MimeMessage(session);   
        DataHandler handler = new DataHandler(new ByteArrayDataSource(parms[1].getBytes(), "text/plain"));   
        message.setSender(new InternetAddress(parms[2]));   
        message.setSubject(parms[0]);   
        message.setDataHandler(handler);   
        if (parms[2].indexOf(',') > 0)   
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(parms[2]));   
        else  
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(parms[2]));   
        Transport.send(message);  
        return "SUC";
} catch (Exception e) {
    e.printStackTrace();
    /*
    * Remember this exception for when onPostExecute is called.
    */
    this.lastException = e;
    return "FLD";
}

}

然后检查onPostExecute()中的lastException状态:

protected void onPostExecute(String s) {
    if (lastException != null) {
        // Do the notification here. You might need to set a context field on this
        // AsyncTask prior to invoking it if you need this here.
    }
}

答案 1 :(得分:0)

首先,您应该在构造函数中传递一个context参数:

private Context mContext;

public AsyncSendEmail(Context context, Session _session)
{
  mContext = context;
  session = _session;
}

然后,只要您需要上下文(例如创建通知),就可以在课程中引用mContext

要存储成功/失败,我会向类添加一个布尔属性(可能是mSuccess)并在检测到(doInBackground()内)消息成功后将其设置为true发送。

然后,覆盖onPostExecute()

@Override
protected void onPostExecute(String s) {
  if (mSuccess) {
    // Do something when the email has been successfully sent
  }
  else {
    // Show error notification
  }
}

请记住,doInBackground()在后​​台线程上执行,但onPostExecute()doInBackground()完成运行后在主/ UI线程上执行。

答案 2 :(得分:0)

AsyncTask的onPostExecute()方法用于向用户提供有关AsyncTask内发生的事情的输出。因为你不能将异常传递给onPostEexecute()(理论上,你可以 - 但显然传递结果也不例外),你的情况下最好的选择是根据是否设置一个标志传递或失败的方法然后在onPostExecute()中读取此标志,然后继续执行您需要执行的操作。