2010-08-04 123 views
1

有时当我在Android开发环境中使用GMailReader尝试javamail/gmail store.connect时,得到“Host is unresolved:imap.gmail.com:993” 。为什么有时会失败,而不是其他人呢?主机未解决:imap.gmail.com:993

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

更新:我没有看到这个问题上的N1,所以它可能是在开发环境中不能在目标上重现的缺陷。 – jacknad 2010-08-12 12:04:38

回答

1

我可能已经打开了太多的GMailReader实例,并没有正确关闭它们。自从我将这个创作者公开化之后,我还没有看到过这个问题,并且增加了一个非常接近的方法。这似乎是这样工作:

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); 
     } 
    } 
...