AsyncTask运行时异常

时间:2013-09-21 08:19:17

标签: android android-asynctask

我正在通过GMail测试一个简单的电子邮件发件人。 代码工作,现在我试图把它放在AsyncTask中,这样我就可以显示一个加载器或做其他东西。

这是工作代码

package com.example.mailsend;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.Menu;
import android.view.View;

public class MailSendMainActivity extends Activity {

String username = "USER";
String password = "PASS";

public void send(View view){
     Properties props = new Properties();
      props.put("mail.smtp.host", "smtp.gmail.com");
      props.put("mail.smtp.socketFactory.port", "465");
      props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.port", "465");

      Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
                        protected PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication(username, password);
      }
      });
      try {

          Message message = new MimeMessage(session);
          message.setFrom(new InternetAddress("Address"));
          message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@hotmail.com"));
          message.setSubject("Subject");
          message.setContent("content", "text/html; charset=utf-8");
          Transport.send(message);

            } catch (MessagingException e) {
                  throw new RuntimeException(e);
                  }

}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mail_send_main);


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.mail_send_main, menu);
    return true;
}



}

现在,我正好无法理解我在做什么。 我试着四处阅读,但我无法抓住它,所以这是我最好的尝试(不工作)

package com.example.mailsend;

import java.io.UnsupportedEncodingException;
import java.util.Properties;


import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException; 
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MailSendMainActivity extends Activity {

String username = "USER";
String password = "PASS";
Toast toast_pre;
Toast toast_post;

private Session createSessionObject(){
    Properties props = new Properties();
      props.put("mail.smtp.host", "smtp.gmail.com");
      props.put("mail.smtp.socketFactory.port", "465");
      props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.port", "465");

      return Session.getInstance(props, new javax.mail.Authenticator() {
      protected PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication(username, password);
      }
      });
   }

private Message createMessage(String email, String subject, String messageBody, Session session) throws MessagingException, UnsupportedEncodingException {
    try {
    Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress("Address"));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@hotmail.com"));
      message.setSubject("Subject");
      message.setContent("content", "text/html; charset=utf-8");
      return message;
    } catch (MessagingException e) {
      throw new RuntimeException(e);
      }

}
private class SendMailTask extends AsyncTask<Message, Void, Void> {
    private ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = ProgressDialog.show(MailSendMainActivity.this, "Please wait", "Sending mail", true, false);
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        progressDialog.dismiss();
    }

    @Override
    protected Void doInBackground(Message... messages) {
        try {
            Transport.send(messages[0]);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
public void send(View view){
    new SendMailTask().execute();

}
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mail_send_main);
    //if (android.os.Build.VERSION.SDK_INT > 9) {
    //    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    //    StrictMode.setThreadPolicy(policy);
    //  }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.mail_send_main, menu);
    return true;
}



}

这就是LogCat

09-21 14:05:37.408: E/AndroidRuntime(26861): FATAL EXCEPTION: AsyncTask #1
09-21 14:05:37.408: E/AndroidRuntime(26861): java.lang.RuntimeException: An error occured while executing doInBackground()
09-21 14:05:37.408: E/AndroidRuntime(26861):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
09-21 14:05:37.408: E/AndroidRuntime(26861):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
09-21 14:05:37.408: E/AndroidRuntime(26861):    at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
09-21 14:05:37.408: E/AndroidRuntime(26861):    at java.util.concurrent.FutureTask.run(FutureTask.java:239)
09-21 14:05:37.408: E/AndroidRuntime(26861):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-21 14:05:37.408: E/AndroidRuntime(26861):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
09-21 14:05:37.408: E/AndroidRuntime(26861):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
09-21 14:05:37.408: E/AndroidRuntime(26861):    at java.lang.Thread.run(Thread.java:841)
09-21 14:05:37.408: E/AndroidRuntime(26861): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
09-21 14:05:37.408: E/AndroidRuntime(26861):    at com.example.mailsend.MailSendMainActivity$SendMailTask.doInBackground(MailSendMainActivity.java:79)
09-21 14:05:37.408: E/AndroidRuntime(26861):    at com.example.mailsend.MailSendMainActivity$SendMailTask.doInBackground(MailSendMainActivity.java:1)
09-21 14:05:37.408: E/AndroidRuntime(26861):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-21 14:05:37.408: E/AndroidRuntime(26861):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
09-21 14:05:37.408: E/AndroidRuntime(26861):    ... 4 more
09-21 14:05:38.009: E/WindowManager(26861): Activity com.example.mailsend.MailSendMainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41e7efa8 V.E..... R......D 0,0-729,324} that was originally added here
09-21 14:05:38.009: E/WindowManager(26861): android.view.WindowLeaked: Activity com.example.mailsend.MailSendMainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41e7efa8 V.E..... R......D 0,0-729,324} that was originally added here
09-21 14:05:38.009: E/WindowManager(26861):     at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
09-21 14:05:38.009: E/WindowManager(26861):     at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
09-21 14:05:38.009: E/WindowManager(26861):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
09-21 14:05:38.009: E/WindowManager(26861):     at android.app.Dialog.show(Dialog.java:281)
09-21 14:05:38.009: E/WindowManager(26861):     at android.app.ProgressDialog.show(ProgressDialog.java:116)
09-21 14:05:38.009: E/WindowManager(26861):     at android.app.ProgressDialog.show(ProgressDialog.java:104)
09-21 14:05:38.009: E/WindowManager(26861):     at com.example.mailsend.MailSendMainActivity$SendMailTask.onPreExecute(MailSendMainActivity.java:67)
09-21 14:05:38.009: E/WindowManager(26861):     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
09-21 14:05:38.009: E/WindowManager(26861):     at android.os.AsyncTask.execute(AsyncTask.java:534)
09-21 14:05:38.009: E/WindowManager(26861):     at com.example.mailsend.MailSendMainActivity.send(MailSendMainActivity.java:87)
09-21 14:05:38.009: E/WindowManager(26861):     at java.lang.reflect.Method.invokeNative(Native Method)
09-21 14:05:38.009: E/WindowManager(26861):     at java.lang.reflect.Method.invoke(Method.java:525)
09-21 14:05:38.009: E/WindowManager(26861):     at android.view.View$1.onClick(View.java:3628)
09-21 14:05:38.009: E/WindowManager(26861):     at android.view.View.performClick(View.java:4240)
09-21 14:05:38.009: E/WindowManager(26861):     at android.view.View$PerformClick.run(View.java:17721)
09-21 14:05:38.009: E/WindowManager(26861):     at android.os.Handler.handleCallback(Handler.java:730)
09-21 14:05:38.009: E/WindowManager(26861):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-21 14:05:38.009: E/WindowManager(26861):     at android.os.Looper.loop(Looper.java:137)
09-21 14:05:38.009: E/WindowManager(26861):     at android.app.ActivityThread.main(ActivityThread.java:5103)
09-21 14:05:38.009: E/WindowManager(26861):     at java.lang.reflect.Method.invokeNative(Native Method)
09-21 14:05:38.009: E/WindowManager(26861):     at java.lang.reflect.Method.invoke(Method.java:525)
09-21 14:05:38.009: E/WindowManager(26861):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-21 14:05:38.009: E/WindowManager(26861):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-21 14:05:38.009: E/WindowManager(26861):     at dalvik.system.NativeStart.main(Native Method)

任何人都可以帮助我吗? 非常感谢你

2 个答案:

答案 0 :(得分:1)

你没有在SendMailTask​​()中传递Message变量.execute();并在Transport.send(messages [0])中使用messages [0];所以你有错误

答案 1 :(得分:0)

当我查看你的代码时,看起来你有两个问题和一件我不理解的事情。

  1. 您在IndexOutOfBound行中获得Transport.send(messages[0]);,因为没有传递任何消息。消息必须来自new SendMailTask().execute();。在这里,您必须传递一条或多条消息。在doInBackground中,您应该像for(Message message : messages) Transport.send(message);

  2. 一样循环播放
  3. 当你遇到第一个问题时,你会得到一个WindowLeaked例外消失。如果不是,我建议将其作为一个额外的问题(然后当邮寄本身有效时)

  4. 我查看了您的代码,并且不明白您调用send()方法的位置,而new SendMailTask().execute();方法又会调用{{1}}。我该怎么监督?简短评论会没问题。