【问题标题】:ContentObserver onChange while still working on previous onChangeContentObserver onChange,同时仍在处理以前的 onChange
【发布时间】:2017-07-07 20:17:51
【问题描述】:

我的应用通过远程命令将联系人添加到电话簿。一个命令可以添加的联系人数量没有限制。

应用程序使用服务内的 ContentObserver 侦听添加的联系人的更改。 onChange() 的处理可能需要一些时间,因为 App 需要查找更新了哪些联系人以及哪些字段受到了影响。

问题是,当接收到一次添加多个联系人(例如 200)的命令时,ContentObserver 会收到重叠的 onChange()。也就是说,当它仍在处理前一个时,它会获取 onChange()。这种重叠会导致问题。

处理这个问题的最佳方法是什么?

理想情况下,我想要的是:如果在处理前一个时发生新的 onChange(),则丢弃前一个的工作并从新的开始。但是该怎么做呢?

【问题讨论】:

    标签: android contentobserver


    【解决方案1】:

    我遇到了同样的问题,我解决了这样的问题,例如如果你有 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;
            }
        }
    

    【讨论】:

    • 感谢@MuthukrishnanRajendran。我在我的代码中实现了你的答案,它解决了当前的问题。但是,由于 onChange() 可能需要很长时间才能完成,所以当再次调用 sendDelayAction 时,可能会出现 timerTask 已经在运行的情况。我会研究如何解决这个问题。
    • 哦,好的,对我来说它工作得很好,几年前我就这样做了,直到现在我没有遇到任何问题,但是如果你找到任何解决方案,请告诉我。这样我也可以在我的应用中申请。
    猜你喜欢
    • 2014-02-18
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多