public class GMailReader extends javax.mail.Authenticator {
private String user;
private String password;
public GMailReader(String user, String password) {
this.user = user;
this.password = password;
}
public int getUnreadMessageCount() throws Exception {
try {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getInstance(props, this);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", user, password);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
int unreadMessageCount = inbox.getUnreadMessageCount();
return unreadMessageCount;
} catch (Exception e) {
Log.e("getUnreadMessageCount", e.getMessage(), e);
return -1;
}
}
答案 0 :(得分:1)
我可能打开过多的GMailReader实例,而不是正确关闭它们。我在一段时间内没有看到这个问题,因为我将创建者移开了,并添加了一个close方法。它似乎运行良好:
public class GMailReader extends javax.mail.Authenticator {
private String user;
private String password;
private Properties properties;
private Session session;
private Store store;
private Folder inbox;
public GMailReader(String user, String password) {
this.user = user;
this.password = password;
}
public void open() throws Exception {
try {
properties = new Properties();
properties.setProperty("mail.store.protocol", "imaps");
session = Session.getInstance(properties, this);
store = session.getStore("imaps");
store.connect("imap.gmail.com", user, password);
inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
} catch (Exception e) {
Log.e(this.getClass().toString(), e.getMessage(), e);
}
}
public void close(boolean expunge) throws Exception {
try {
if (inbox.isOpen()) {
inbox.close(expunge);
}
if (store.isConnected()) {
store.close();
}
} catch (Exception e) {
Log.e(this.getClass().toString(), e.getMessage(), e);
}
}
...