我有这个类用于发送带有android的电子邮件
public class SendMailTask extends AsyncTask {
private ProgressDialog statusDialog;
private Activity sendMailActivity;
public SendMailTask(Activity activity) {
sendMailActivity = activity;
}
protected void onPreExecute() {
statusDialog = new ProgressDialog(sendMailActivity);
statusDialog.setMessage("Getting ready...");
statusDialog.setIndeterminate(false);
statusDialog.setCancelable(false);
statusDialog.show();
}
@Override
protected Object doInBackground(Object... args) {
try {
Log.i("SendMailTask", "About to instantiate GMail...");
publishProgress("Processing input....");
GMail androidEmail = new GMail(args[0].toString(),
args[1].toString(), (List) args[2], args[3].toString(),
args[4].toString());
publishProgress("Preparing mail message....");
androidEmail.createEmailMessage();
publishProgress("Invio email in corso, sarai ricontattato da un nostro operatore per la conferma");
androidEmail.sendEmail();
publishProgress("Email Sent.");
Log.i("SendMailTask", "Mail Sent.");
} catch (Exception e) {
publishProgress(e.getMessage());
Log.e("SendMailTask", e.getMessage(), e);
}
return null;
}
@Override
public void onProgressUpdate(Object... values) {
statusDialog.setMessage(values[0].toString());
}
@Override
public void onPostExecute(Object result) {
statusDialog.dismiss();
}
}
不使用片段我在MainActivity中使用以下代码发送邮件
new SendMailTask(MainActivity.this).execute(fromEmail,
fromPassword, toEmailList, emailSubject, emailBody);
但现在我需要使用Fragment,此时我收到错误: “MainActivity.this它不是一个封闭的类”
我该如何解决这个错误?
P.S。:对不起,我的英文不好:D
答案 0 :(得分:13)
更改以下代码
new SendMailTask(MainActivity.this).execute(fromEmail,
fromPassword, toEmailList, emailSubject, emailBody);
要
new SendMailTask(getActivity()).execute(fromEmail,
fromPassword, toEmailList, emailSubject, emailBody);
有关详细信息,请查看以下链接。
答案 1 :(得分:12)
从片段到活动使用此:
((YourActivityName)getActivity()).yourPublicMethod();
从活动到片段使用:
FragmentManager fragmentManager = getSupportFragmentManager();
//include fragment via layout xml
YourFragmentClass fragment = (YourFragmentClass)fragmentManager.findFragmentById(R.id.your_fragment_id);
fragment.yourPublicMethod();