问题
I know how to retrieve the contacts from the user device. But I wonder if there is a way to query the contacts table and get only the newest contacts that were added?
What I'm trying to do is that:
In my application I read the contacts from the device and save them in my application's DB, so the user can select which are the favorites contact in this application. And the next time the user enters to the contact activity, I read the data from the DB.
Now, I want to add a refresh button, so when the user clicks on it, the contact list will updated with the new contacts.. so instead of reading again the whole contacts table.. I want to retreive only the newest contacts that were added or the ones that were changed (in the device).
is there any way to acheive this?
The only fields I see that are somehow related to this question are "VERSION
"
and "DATA_VERSION
"
So I guess I need to save in my DB also the VERSION for each contact row and when to user clickes on refresh I need to compare this in order to see if there was any change.. but in this case I need again to read the entire contacts from the device...
回答1:
You can achieve using ContentObserver
, But you can't get which contact updated, you can get only notify that your native contact is updated.
getContentResolver().registerContentObserver(
ContactsContract.Contacts.CONTENT_URI, false, new AddressBookContentObserver());
/**
* Content observer for Address book contacts change notification.
*
* @author malik
*/
public class AddressBookContentObserver extends ContentObserver {
public AddressBookContentObserver() {
super(null);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
if (DBG) {
ZKLog.d(TAG, "Contacts changes event.");
}
// 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
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// go through all the contact and check which one is missing or modified or added from your database.
}
}, 1000);
}
@Override
public boolean deliverSelfNotifications() {
return true;
}
}
Note :
We can't get which contact is added, modified or deleted
回答2:
Starting with API level 18, you can use Contacts.CONTACT_LAST_UPDATED_TIMESTAMP, so it's possible to query for all contacts that had been modified (or created) recently, and compare only those to your last cache of contact ids, and the delta would be the contacts created since the last time your code ran.
来源:https://stackoverflow.com/questions/45658649/android-get-only-newest-contacts-that-were-added