2017-07-07 86 views
0

我的應用程序通過遠程命令將聯繫人添加到電話簿。使用一個命令可以添加的聯繫人數量沒有限制。ContentObserver onChange同時仍在處理上一個onChange

該應用程序監聽使用服務中的ContentObserver添加的聯繫人的更改。 onChange()的處理可能需要一些時間,因爲App需要查找哪個聯繫人已更新以及哪些字段受到影響。

問題是,當收到一次添加許多聯繫人(例如200)的命令時,ContentObserver接收到重疊的onChange()。這是,它仍然在onChange(),而它仍然在前一個工作。這種重疊會導致問題。

處理這個問題的最佳方法是什麼?理想情況下,我想要的是:如果新的onChange()在前一個正在處理時發生,那麼放棄前一個工作並從新的開始。但如何做到這一點?

回答

0

我面臨同樣的問題,我解決了這樣的問題,例如,如果你有10次聯繫更改,第一次聯繫更新將得到onChange但本地聯繫,它將需要大約1秒,所以我們有足夠的延遲在此之前更新,如果我們得到下一次聯繫人更新,它將取消前一個定時器,並且它將自己啓動,所以我們只有在所有聯繫人更新後才能獲得run方法。

private Timer waitingTimer; 

    private Timer waitingSMSTimer; 

    private Timer waitingVoiceMailTimer; 

    private void sendDelayAction() { 

     if (waitingTimer != null) { 
      waitingTimer.cancel(); 

      /** 
      * Timer in Java will throw IllegalStateException if you try to schedule task on a Timer 
      * which has been cancelled or whose Task execution Thread has been terminated. so we 
      * are making null and create timer every time. 
      */ 
      waitingTimer = null; 
     } 

     waitingTimer = new Timer(); 

     final TimerTask timerTask = new TimerTask() { 

      @Override 
      public void run() { 
       // Do your action here. 
      } 
     }; 

     waitingTimer.schedule(timerTask, 1500); 
    } 

    /** 
    * Content observer for Address book contacts change notification. 
    */ 
    public class AddressBookContentObserver extends ContentObserver { 
     public AddressBookContentObserver() { 
      super(null); 
     } 

     @Override 
     public void onChange(boolean selfChange) { 
      super.onChange(selfChange); 
      // We are waiting for some time, Native contact taking some time ot update, before that 
      // if we try to fetch the contact, its not returning the newly added contact 
      sendDelayAction(); 
     } 

     @Override 
     public boolean deliverSelfNotifications() { 
      return true; 
     } 
    } 
+0

Thanks @MuthukrishnanRajendran。我在我的代碼中實現了你的答案,它解決了當前的問題。但是,由於onChange()可能需要很長時間才能完成,因此會再次調用** sendDelayAction **時會發生** timerTask **已經運行的情況。我會研究如何解決這個問題。 – user2795888

+0

哦,對我來說,它工作的很好,我在幾年前就做了這件事,直到現在我還沒有遇到任何問題,但請讓我知道,如果你找到任何解決方案。這樣我也可以在我的應用程序中應用。 –