我面臨同樣的問題,我解決了這樣的問題,例如,如果你有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;
}
}
Thanks @MuthukrishnanRajendran。我在我的代碼中實現了你的答案,它解決了當前的問題。但是,由於onChange()可能需要很長時間才能完成,因此會再次調用** sendDelayAction **時會發生** timerTask **已經運行的情況。我會研究如何解決這個問題。 – user2795888
哦,對我來說,它工作的很好,我在幾年前就做了這件事,直到現在我還沒有遇到任何問題,但請讓我知道,如果你找到任何解決方案。這樣我也可以在我的應用程序中應用。 –