如何发送电子邮件非活动?

时间:2012-11-12 13:10:08

标签: java android android-intent

我需要发送电子邮件,所以我创建了一个类,但是在startActivity(intent)中出现了错误。此代码在主活动中运行良好。这里是代码:

public class SendEmail extends Activity {
private String emailTo;
private String subject;
private String message;

public SendEmail(String AEmailTo, String ASubject, String AMessage) {
    this.emailTo = AEmailTo;
    this.subject = ASubject;
    this.message = AMessage;
}

public void Send(){
     try {          
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("application/octet-stream");
        intent.putExtra(Intent.EXTRA_SUBJECT, this.subject);
        intent.putExtra(Intent.EXTRA_TEXT, this.message);
        intent.putExtra(Intent.EXTRA_EMAIL, new String[] {this.emailTo});
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
       } catch (Exception e) {   
         Log.e("SendMail", e.getMessage(), e);   
       }
    }

}

logcat的:

11-12 10:54:56.783: E/SendMail(19773): null
11-12 10:54:56.783: E/SendMail(19773): java.lang.NullPointerException
11-12 10:54:56.783: E/SendMail(19773):  at    android.app.Activity.startActivityForResult(Activity.java:2817)
11-12 10:54:56.783: E/SendMail(19773):  at    android.app.Activity.startActivity(Activity.java:2923)
11-12 10:54:56.783: E/SendMail(19773):  at   idealbrasil.forcav.android.SendEmail.Send(SendEmail.java:52)
11-12 10:54:56.783: E/SendMail(19773):  at idealbrasil.forcav.android.util.funcoes.SendEmail(funcoes.java:221)
11-12 10:54:56.783: E/SendMail(19773):  at idealbrasil.forcav.android.util.TrataErro$1.onClick(TrataErro.java:136)
11-12 10:54:56.783: E/SendMail(19773):  at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:158)
11-12 10:54:56.783: E/SendMail(19773):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-12 10:54:56.783: E/SendMail(19773):  at android.os.Looper.loop(Looper.java:123)
11-12 10:54:56.783: E/SendMail(19773):  at android.app.ActivityThread.main(ActivityThread.java:4627)

1 个答案:

答案 0 :(得分:0)

对于startActivity(),上下文为null,这是您获得nullpointer异常的原因。看起来您是Android的新手,并且该过程不符合编码惯例。

您可以在类中使用onCreate()方法,然后使用类startActivity(),或者将上下文传递给此函数,并调用

context.startActivity(intent);