我正在开发一个Android应用程序。连接到gmail服务器和读取收件箱电子邮件。我实现连接和电子邮件阅读代码,但问题是,当应用程序。正在与应用程序的gmail服务器连接。挂起,当它从gmail服务器读取电子邮件时,它会停止工作一段时间然后正常运行。我想使用asyntask在后台放置连接和读取电子邮件代码。 请告诉我如何在android中使用asyntask实现连接和读取电子邮件代码,以便我的应用程序。不会挂起或崩溃或停止?
public void readGmail(String host, String storeType, String user, String password, SQLiteDatabase database) {
try {
Properties properties = new Properties();
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
store = emailSession.getStore("pop3s");
store.connect(host, user, password);
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
Message[] messages = emailFolder.getMessages();
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
Object obj = message.getContent();
int Email = message.getMessageNumber();
String subject = message.getSubject();
String emailDateTime = String.valueOf(message.getSentDate());
String from = String.valueOf(message.getFrom()[0]);
String sendFrom=from.substring(from.indexOf("<") + 1, from.indexOf(">"));
Multipart mp = (Multipart) message.getContent();
BodyPart bp = ((Multipart) message.getContent()).getBodyPart(0);
if (bp.isMimeType("text/plain")) {
String body = (String) bp.getContent();
AddEmail addEmail = new AddEmail();
DbHelper dbHelper = new DbHelper(getApplicationContext());
//SQLiteDatabase database = dbHelper.getWritableDatabase();
addEmail.EmailInsert(sendFrom, subject, body, emailDateTime, "Pending...", "", Data.getUserEmail, Data.getUserPassword, database);
}
}
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
System.out.println("Email Number " + (i + 1));
}
//SMSSendActivity smsSendActivity = new SMSSendActivity();
//smsSendActivity.SMSPerodicTimer(database);
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}