我对使用AsyncTask
Android sdk 提供的类有疑问。我正在我的代码中从活动中开始一项任务,该活动的工作是定期发送电子邮件(根据指定的时间)。我在中重新启动任务onPostExecute()
。它确实会定期发送电子邮件,但一段时间后电子邮件停止发送。按后退键有影响吗?
我正在浏览AsyncTask上的以下链接,发现AsyncTask
在活动的方向改变或失焦后需要刷新。我需要单独处理吗?context
每次activity
失焦或其方向发生变化时,我是否需要刷新?我正在根据上下文进行某些数据库操作。
这是我的AsyncTask
代码:
public class SendEmailTask extends AsyncTask<String, Void, String> {
private static final String LOG_TAG = "EmailTask";
private static final int MESSAGE_SENT = StringConstants.CONSTANT_YES_FLAG;
private Context context;
public SendEmailTask(Context context) {
this.context = context;
}
@Override
protected String doInBackground(String... time) {
// String message = "Message sent at ";
try{
//DB operations
Validator validator = new Validator(context);
int emailInterval = validator.validForSendingEmail(settingsMap);
String emailId = settingsMap.get(DBSetting.COLUMN_EMAILID);
String emailPwd = settingsMap.get(DBSetting.COLUMN_EMAIL_PWD);
if (emailId != null && emailPwd != null && emailInterval > 0) {
Thread.sleep((Integer.valueOf(emailInterval) * 60000));
// TODO: formatting of email body
DALLog dalLog = DALLog.getDALLogInstance();
dalLog.init(context);
GMailSender sender = new GMailSender(emailId, emailPwd);
sender.sendMail("Mail From Auto responder",
result, emailId,
emailId);
dalLog.close();
}
return null;
}
catch (NumberFormatException e) {
e.printStackTrace();
Log.d(LOG_TAG, e.getMessage());
}
catch (InterruptedException e) {
e.printStackTrace();
Log.d(LOG_TAG, e.getMessage());
}
catch (Exception e) {
Log.d(LOG_TAG, e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(String result) {
//DB operations
Validator validator = new Validator(context);
int emailInterval = validator.validForSendingEmail(settingsMap);
// Start EmailTask thread if not started already
SendEmailTask emailTask = new SendEmailTask(context);
if (emailTask.getStatus() != AsyncTask.Status.RUNNING) {
emailTask.execute(new String[]{});
}
}
}