[英]Android JavaMail Detect If Server Goes Offline
I'm currently developing an email application with a background service used in conjunction with the JavaMail Idle functionality. 我目前正在开发带有后台服务和JavaMail Idle功能一起使用的电子邮件应用程序。 The background service keeps the idle functionality working by issuing a check every 29 minutes (as the server being used (Exchange server)) can sometimes drop the connection after 30 minutes of being connected. 后台服务通过每29分钟发出一次检查来保持空闲功能正常工作(因为正在使用的服务器(Exchange服务器))有时在连接30分钟后会断开连接。
Whilst this works perfectly, if the Exchange server is offline, then the application will continue to attempt to reconnect to the IMAP folder indefinately. 尽管这可以正常运行,但如果Exchange服务器处于脱机状态,则应用程序将继续尝试无限期地重新连接到IMAP文件夹。 I have noticed spikes in data usage between the hours of 3AM & 6AM (a typical Exchange update time). 我注意到3AM和6AM(典型的Exchange更新时间)之间的数据使用量激增。
To avoid the increased data usage, I am looking to implement functionality where the app should attempt to reconnect to the IMAP folder three times and then display a warning to the user that the server is offline and a new connection attempt will be retried in 30 minutes. 为了避免增加数据使用量,我正在寻求实现一些功能,使应用程序应尝试三遍重新连接到IMAP文件夹,然后向用户显示警告,表明服务器处于脱机状态,并且将在30分钟内重试一次新的连接。
In order to achieve this, how would I be able to detect if the Exchange server is actually offline/updating & would any exceptions be thrown, if the app cannot connect to the IMAP folder? 为了实现此目的,如果应用程序无法连接到IMAP文件夹,我将如何检测Exchange服务器是否实际上处于脱机/更新状态,并且会引发任何异常? As if an exception would be thrown, then I could save a local int variable and increment it by one every time the exception is thrown and then show the alert to the user on the third time. 好像会引发异常,那么我可以保存一个本地int变量,并在每次引发异常时将其递增1,然后在第三次向用户显示警报。
My current code implementation can be seen below: 我当前的代码实现如下所示:
public void checkInboxEmail(final String host, final String user, final String password) {
Log.d(TAG, "checkEmail");
this.host = host;
this.user = user;
this.password = password;
new Thread(new Runnable() {
@Override
public void run() {
try {
Log.d(TAG, "checkEmail - run()");
long databaseRecords;
//create properties field
Properties properties = new Properties();
properties.put("mail.store.protocol", "imaps");
properties.put("mail.imaps.ssl.trust", "*");
properties.put("mail.debug", "true");
emailSession = Session.getInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
IMAPStore imapStore = (IMAPStore) emailSession.getStore("imaps");
// imapStore.connect();
imapStore.connect(host, user, password);
if (imapStore.isConnected()) {
Log.d("MailPush", "Successfully connected to IMAP");
} else {
Log.d("MailPush", "Not connected to IMAP");
}
final IMAPFolder folder = (IMAPFolder) imapStore.getFolder("Inbox");
folder.open(IMAPFolder.READ_WRITE);
databaseRecords = dbManager.getReceivedEmailRecordsCount();
if (databaseRecords < folder.getMessageCount()) {
Log.d(TAG, "Receiving Mail...");
receiveMail(folder.getMessages());
} else {
Log.d(TAG, "Records match.");
}
Folder[] fdr = imapStore.getDefaultFolder().list();
for (Folder fd : fdr)
System.out.println(">> " + fd.getName());
folder.addMessageCountListener(new MessageCountListener() {
public void messagesAdded(MessageCountEvent e) {
System.out.println("Message Added Event Fired");
Log.d(TAG, "MESSAGE TYPE: " + e.getType());
//ADDED = 1 & REMOVED = 2
try {
Message[] messages = e.getMessages();
System.out.println("messages.length---" + messages.length);
for (Message message : messages) {
if (!message.getFlags().contains(Flags.Flag.SEEN)) {
//Message is new (hasn't been seen) > Message Details
System.out.println("---------------------------------");
System.out.println("Email Number " + (message.getMessageNumber()));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
String from = message.getFrom()[0].toString();
String cc = InternetAddress.toString(message.getRecipients(Message.RecipientType.CC));
Log.d(TAG, "CC 1: " + cc);
Address[] recipients = message.getRecipients(Message.RecipientType.CC);
cc = InternetAddress.toString(recipients);
Log.d(TAG, "CC 2: " + cc);
//Check Encryption Details > Add SEEN Flag > Add to database
checkEncryption((MimeMessage) message, from, cc);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void messagesRemoved(MessageCountEvent e) {
System.out.println("Message Removed Event fired");
}
});
folder.addMessageChangedListener(new MessageChangedListener() {
public void messageChanged(MessageChangedEvent e) {
System.out.println("Message Changed Event fired");
}
});
startListening(folder);
//close the store and folder objects
// emailFolder.close(false);
// store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
private void startListening(IMAPFolder imapFolder) {
Log.d(TAG, "startListening");
// We need to create a new thread to keep alive the connection
Thread t = new Thread(
new KeepAliveRunnable(imapFolder), "IdleConnectionKeepAlive"
);
t.start();
while (!Thread.interrupted()) {
Log.d(TAG, "Starting IDLE");
try {
Log.d(TAG, "Setting IDLE");
imapFolder.idle();
} catch (FolderClosedException fex) {
//Server closes connection.
Log.d(TAG, "FolderClosedException. Server potentially dropped connection. Retrying connection...");
fex.printStackTrace();
if (!isServiceRunning(MyService.class)) {
Log.d(TAG, "Service isn't running. Starting service...");
//Start service
Intent intent = new Intent(context, MyService.class);
intent.putExtra("host", host);
intent.putExtra("email", user);
intent.putExtra("password", password);
context.startService(intent);
} else {
Log.d(TAG, "Service is already running. Checking email...");
checkInboxEmail(host, user, password);
}
} catch (MessagingException e) {
//Idle isn't supported by server.
Log.d(TAG, "Messaging exception during IDLE: ");
e.printStackTrace();
}
}
// Shutdown keep alive thread
if (t.isAlive()) {
Log.d(TAG, "Interrupting thread");
t.interrupt();
}
}
private static class KeepAliveRunnable implements Runnable {
private final String TAG = getClass().getName();
private static final long KEEP_ALIVE_FREQ = 60000 * 29; // 29 minutes (Exchange connection drops after 20-30 minutes)
private IMAPFolder folder;
KeepAliveRunnable(IMAPFolder folder) {
this.folder = folder;
}
@Override
public void run() {
while (!Thread.interrupted()) {
try {
Thread.sleep(KEEP_ALIVE_FREQ);
// Perform a messageCount check just to keep alive the connection
Log.d(TAG, "Performing a messageCount check to keep the connection alive");
folder.getMessageCount();
} catch (InterruptedException e) {
// Ignore, just aborting the thread...
Log.d(TAG, "Interrupted...");
e.printStackTrace();
} catch (MessagingException e) {
// Shouldn't really happen...
Log.d(TAG, "Unexpected exception while keeping alive the IDLE connection");
e.printStackTrace();
}
}
}
}
private void receiveMail(Message[] messages) {
try {
System.out.println("messages.length---" + messages.length);
for (Message message : messages) {
if (!message.getFlags().contains(Flags.Flag.SEEN)) {
//Message is new (hasn't been seen) > Message Details
System.out.println("---------------------------------");
System.out.println("Email Number " + (message.getMessageNumber()));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
String from = message.getFrom()[0].toString();
String cc = InternetAddress.toString(message.getRecipients(Message.RecipientType.CC));
//Check Encryption Details > Add SEEN Flag > Add to database
checkEncryption((MimeMessage) message, from, cc);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
If the server is up but not accepting connections, the connect will fail immediately (with an exception). 如果服务器已启动但不接受连接,则连接将立即失败(例外)。 If the server is down, and you've set a connect timeout, the connect will fail after the timeout (with an exception). 如果服务器已关闭,并且您设置了连接超时,则超时后连接将失败(例外)。
To clarify @BillShannon's answer, if the server host is up but Exchange is not accepting connections, the connect will fail immediately with a ConnectException: connection refused
. 为了阐明@BillShannon的答案,如果服务器主机已启动,但Exchange不接受连接,则连接将立即失败,并显示ConnectException: connection refused
。 If the server host is down, the connect will fail after the timeout with a ConnectException: connect timeout
(or possibly a SocketTimeoutException
), regardless of whether you've set a connect timeout, as the platform always has one. 如果服务器主机已关闭,则连接将在超时后失败,并显示ConnectException: connect timeout
(或可能是SocketTimeoutException
), 无论您是否设置了连接超时,因为平台始终都有一个连接超时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.