2017-10-08 160 views
0

我正在開發一個接收和處理郵件消息的Android應用程序。該應用程序必須連接到IMAP服務器並保持連接處於活動狀態,以便它可以立即查看和處理新郵件(郵件包含來自郵件API服務器的json數據)。該應用程序有兩種模式,手動和實時連接。下面是我的一些代碼:javamail空閒停止觸發消息一段時間後添加,線程鎖定

class Idler { 
Thread th; 
volatile Boolean isIdling=false; 
boolean shouldsync=false;//we need to see if we have unseen mails 
Object idleLock; 
Handler handler=new Handler(); 
IMAPFolder inbox; 
public boolean keppAliveConnection;//keep alive connection, or manual mode 

//This thread should keep the idle connection alive, or in case it's set to manual mode (keppAliveConnection=false) get new mail. 
Thread refreshThread; 
synchronized void refresh() 
{ 
    if(isIdling)//if already idling, just keep connection alive 
    { 
     refreshThread =new Thread(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        inbox.doCommand(new IMAPFolder.ProtocolCommand() { 
         @Override 
         public Object doCommand(IMAPProtocol protocol) throws ProtocolException { 
          //Why not noop? 
          //any call to IMAPFolder.doCommand() will trigger waitIfIdle, this 
          //issues a "DONE" command and waits for idle to return(ideally with a DONE server response). 
          // So... I think NOOP is unnecessary 
          //protocol.simpleCommand("NOOP",null); I'm not issuing noop due to what I said^

          //PD: if connection was broken, then server response will never arrive, and idle will keep running forever 
          //without triggering messagesAdded event any more :'(I see any other explanation to this phenomenon 


          return null; 
         } 
        }); 
       } catch (MessagingException e) { 
        e.printStackTrace(); 
       } 
      } 
     },"SyncThread"); 
     refreshThread.start(); 
    } 
    else 
    { 
     getNewMail();//If manual mode keppAliveConnection=false) get the new mail 
    } 
} 
public Idler() 
{ 
    th=new Thread(new Runnable() { 

     @SuppressWarnings("InfiniteLoopStatement") 
     @Override 
     public void run() { 
      while (true) 
      { 
       try { 
        if(refreshThread !=null && refreshThread.isAlive()) 
         refreshThread.interrupt();//if the refresher thread is active: interrupt. I thing this is not necessary at this point, but not shure 
        initIMAP();//initializes imap store 
        try { 
         shouldsync=connectIMAP()||shouldsync;//if was disconnected or ordered to sync: needs to sync 
        } 
        catch (Exception e) 
        { 
         Thread.sleep(5000);//if can't connect: wait some time and throw 
         throw e; 
        } 
        shouldsync=initInbox()||shouldsync;//if inbox was null or closed: needs to sync 
        if(shouldsync)//if needs to sync 
        { 
         getNewMail();//gets new unseen mail 
         shouldsync=false;//already refreshed, clear sync "flag" 
        } 

        while (keppAliveConnection) {//if sould keep idling "forever" 
         synchronized (idleLock){}//MessageCountListener may be doing some work... wait for it 
         isIdling = true; //set isIdling "flag" 
         handler.removeCallbacksAndMessages(null);//clears refresh scheduled tasks 
         handler.postDelayed(new Runnable() { 
          @Override 
          public void run() { 
           refresh(); 
          } 
         },1200000);//Schedule a refresh in 20 minutes 
         inbox.idle();//start idling 
         if(refreshThread !=null && refreshThread.isAlive()) 
          refreshThread.interrupt();//if the refresher thread is active: interrupt. I thing this is not necessary at this point, but not shure 
         handler.removeCallbacksAndMessages(null);//clears refresh scheduled tasks 
         isIdling=false;//clear isIdling "flag" 
         if(shouldsync) 
          break;//if ordered to sync... break. The loop will handle it upstairs. 
         synchronized (idleLock){}//MessageCountListener may be doing some work... wait for it 

        } 
       } 
       catch (Exception e) { 
        //if the refresher thread is active: interrupt 
        //Why interrupt? refresher thread may be waiting for idle to return after "DONE" command, but if folder was closed and throws 
        //a FolderClosedException, then it could wait forever...., so... interrupt. 
        if (refreshThread != null && refreshThread.isAlive()) 
         refreshThread.interrupt(); 
        handler.removeCallbacksAndMessages(null);//clears refresh scheduled tasks 
       } 
      } 
     } 
    },"IdlerThread"); 
    th.start(); 
} 

private synchronized void getNewMail() 
{ 
    shouldsync=false; 
    long uid=getLastSeen();//get last unprocessed mail 
    SearchTerm searchTerm=new UidTerm(uid,Long.MAX_VALUE);//search from las processed message to the las one. 
    IMAPSearchOperation so=new IMAPSearchOperation(searchTerm); 
    try { 
     so.run();//search new messages 
     final long[] is=so.uids();//get unprocessed messages count 
     if (is.length > 0) {//if some... 
      try { 
       //there are new messages 
       IMAPFetchMessagesOperation fop=new IMAPFetchMessagesOperation(is); 
       fop.run();//fetch new messages 
       if(fop.messages.length>0) 
       { 
        //process fetched messages (internally sets the last seen uid value & delete some...) 
        processMessages(fop.messages); 
       } 
       inbox.expunge();//expunge deleted messages if any 
      } 
      catch (Exception e) 
      { 
       //Do something 
      } 
     } 
     else 
     { 
      //Do something 
     } 
    } 
    catch (Exception e) 
    { 
     //Do something 
    } 
} 


private synchronized void initIMAP() 
{ 
    if(store==null) 
    { 
     store=new IMAPStore(mailSession,new URLName("imap",p.IMAPServer,p.IMAPPort,null,p.IMAPUser,p.IMAPPassword)); 
    } 
} 

private boolean connectIMAP() throws MessagingException { 
    try { 
     store.connect(p.IMAPServer, p.IMAPPort, p.IMAPUser, p.IMAPPassword); 
     return true; 
    } 
    catch (IllegalStateException e) 
    { 
     return false; 
    } 
} 

//returns true if the folder was closed or null 
private synchronized boolean initInbox() throws MessagingException { 
    boolean retVal=false; 
    if(inbox==null) 
    {//if null, create. This is called after initializing store 
     inbox = (IMAPFolder) store.getFolder("INBOX"); 
     inbox.addMessageCountListener(countListener); 
     retVal=true;//was created 
    } 
    if(!inbox.isOpen()) 
    { 
     inbox.open(Folder.READ_WRITE); 
     retVal=true;//was oppened 
    } 
    return retVal; 
} 

private MessageCountListener countListener= new MessageCountAdapter() { 
    @Override 
    public void messagesAdded(MessageCountEvent ev) { 
     synchronized (idleLock) 
     { 
      try { 
       processMessages(ev.getMessages());//process the new messages, (internally sets the last seen uid value & delete some...) 
       inbox.expunge();//expunge deleted messajes if any 
      } catch (MessagingException e) { 
       //Do something 
      } 

     } 
    } 
}; 

}

的問題是:有時,當用戶刷新或應用程序會自動刷新,在活動連接模式,一個或兩個這樣的條件使我應用程序獲取新消息。這是來自javamail的源代碼。

1:IdlerThread進入監視狀態:

//I don't know why sometimes it enters monitor state here. 
private synchronized void throwClosedException(ConnectionException cex) 
     throws FolderClosedException, StoreClosedException { 
// If it's the folder's protocol object, throw a FolderClosedException; 
// otherwise, throw a StoreClosedException. 
// If a command has failed because the connection is closed, 
// the folder will have already been forced closed by the 
// time we get here and our protocol object will have been 
// released, so if we no longer have a protocol object we base 
// this decision on whether we *think* the folder is open. 
if ((protocol != null && cex.getProtocol() == protocol) || 
    (protocol == null && !reallyClosed)) 
     throw new FolderClosedException(this, cex.getMessage()); 
    else 
     throw new StoreClosedException(store, cex.getMessage()); 
} 

2: 「refresherThread」 進入在等待狀態:

void waitIfIdle() throws ProtocolException { 
assert Thread.holdsLock(messageCacheLock); 
while (idleState != RUNNING) { 
    if (idleState == IDLE) { 
    protocol.idleAbort(); 
    idleState = ABORTING; 
    } 
    try { 
    // give up lock and wait to be not idle 
    messageCacheLock.wait();//<-----This is the line is driving me crazy. 
    } catch (InterruptedException ex) { } 
} 
} 

由於兩個這個線程中的一個 「停止」 運行(等待&顯示器狀態)當我的應用程序達到這個條件時是無用的。在我國,移動數據網絡非常不穩定,速度慢(GSM),所以它必須具有故障恢復能力,並注意每個傳輸位。

我想問題出現時,連接默默失敗,並刷新線程開始做它的工作。如果空閒處於活動狀態,它將發出DONE命令,但是,當連接消失時,當空閒嘗試拋出FolderClosedException時,一個或兩個線程將無限期鎖定。

所以,我的問題是:爲什麼會出現這種情況,以及如何防止它?我怎樣才能保持空閒循環安全運行而不被鎖定?

我已經嘗試了很多東西,直到用盡沒有結果。

以下是我讀過的一些線索,但未解決我的問題。在我的國家,互聯網也非常昂貴,所以我無法按照自己的想法進行研究,也沒有列出我訪問過的所有尋找信息的網址。

JavaMail: Keeping IMAPFolder.idle() alive

JavaMail: Keeping IMAPFolder.idle() alive

Javamail : Proper way to issue idle() for IMAPFolder

請原諒我的英語。任何建議將不勝感激。我聽說過這個網站的嚴格性,所以請保持溫柔,我是新來的。

回答

0

一定要設置timeout properties以確保您不會掛起等待死連接或服務器。

而不是直接發出一個nop命令,你應該調用Folder.isOpen或Folder.getMessageCount;他們會根據需要發出nop命令。

如果該文件夾異步關閉(FolderClosedException),則需要重新啓動空閒循環。

+0

事實上,我認爲這發生在某處發生FolderClosedException(太多亂七八糟的調試)時。重新啓動閒置循環是什麼意思? –

+0

如果該文件夾異步關閉,則Folder.idle調用將失敗。由於你忽略了所有的異常,這可能會使該線程處於緊密的循環中。最好是捕獲該異常,重新打開文件夾(如果這是你的意圖),然後重新啓動閒置循環。 –

+0

該代碼大於我發佈的片段。它已經實現了所有這些東西,但我想保持簡短。我想我已經解決了這個問題,但是我認爲發生的事情的「已廢止」解釋並不符合允許的字符數。是否有一些「正確」的方式來添加「更大」的評論? –

相關問題