我有一门课可以发送各种带有附件的邮件。
因为该方法sendEmail(addresses);
需要时间来上传附件和发送电子邮件,所以我创建了一个 AsyncTask 来显示一个等待对话框,
然而,不幸的是,在发送过程中,应用程序会冻结,直到它终止发送而不显示任何内容(或者有时在程序结束前显示一个冻结的等待窗口片刻)
我的类中的相关代码部分如下
public class MyClass extends Activity {
...
private ProgressDialog waitingDialog;
....
OnClickListener mInvia = new OnClickListener() {
public void onClick(View v) {
new MyAsyncTaskClass().execute(new String[] {});
}
};
public void prepareSending() {
String x = "";
for (String s : selectedMails) {
x += (s + ";");
}
String[] addresses = x.split(";");
sendEmail(addresses);
}
private void openFile() {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("file/*");
startActivityForResult(i, FILE_REQ_CODE);
}
protected void onActivityResult(int requestCode, int resultCode,
Intent intentData) {
Uri tmp = intentData.getData();
filePath=getRealPath(tmp);
super.onActivityResult(requestCode, resultCode, intentData);
}
public void sendEmail(String[] addresses) {
Mail m = new Mail("sendermail@sample.com",
"senderpassword");
name = editor1.getText().toString();
subject = editor2.getText().toString();
text = editor3.getText().toString();
emailReply = editor4.getText().toString();
m.setTo(addresses);
m.setFrom(emailReply);
m.setSubject(subject);
m.setBody(text + "\n\n\n Sent by" + name);
try {
m.send();
} catch (Exception e) {
Log.e("MyClass", "Cannot send email", e);
}
try {
m.addAttachment(filePath);
if (m.send()) {
Alerts.Ok(MyClass.this);
nSuccess++;
} else {
Alerts.ErrorSending(MyClass.this);
}
} catch (Exception e) {
Alerts.ErrorAttachment(MyClass.this);
}
}
//inner class that should show a waiting windows
private class MyAsyncTaskClass extends AsyncTask<String, Void, Void> {
@Override
protected void onPreExecute() {
waitingDialog = new ProgressDialog(MyClass.this);
waitingDialog.setMessage("Loading ....");
waitingDialog.setIndeterminate(true);
waitingDialog.setCancelable(true);
waitingDialog.show();
}
@Override
protected Void doInBackground(final String... strings) {
try {
runOnUiThread(new Runnable() {
public void run() {
prepareSending();
}
});
} catch (Exception e) {
}
return null;
}
@Override
protected void onPostExecute(Void params) {
waitingDialog.dismiss();
}
}
//end innerclass
// start context menu code
......
}