Objective: To determine whether the address book has changed
Reference: see the version constant in the ContactsContract. RawContacts class. This value is read-only and changes this value when the address book changes.
Method: The version value corresponds to the data in each address book. If there are 100 entries, there are 100 such values. I said the method used is as follows:
1. Obtain all version values to form a string
2. Because the string may be long, use MD5 to convert the short string.
3. Compare it with the previous string and save the new one to SharedPreferences.
The following three sections of Code show whether the address book is changed.
/*** Get the address book version ** @ return */private String getContactsVersion () {String version = null; StringBuffer sb = new StringBuffer (); Cursor raws = null; try {raws = mContext. getContentResolver (). query (ContactsContract. rawContacts. CONTENT_URI, null, null); while (raws. moveToNext () {version = raws. getString (raws. getColumnIndex (ContactsContract. rawContacts. VERSION); sb. append (version );} } Catch (Exception e) {e. printStackTrace ();} finally {if (raws! = Null) {raws. close () ;}return sb. toString ();}
/*** Convert the String version to the MD5 format ** @ param s * @ return */private String stringToMd5 (String s) {byte [] value = s. getBytes (); try {MessageDigest md = MessageDigest. getInstance ("MD5"); md. update (value); byte [] temp = md. digest (); StringBuilder sb = new StringBuilder (); for (byte B: temp) {sb. append (Integer. toHexString (B & 0xff);} String md5Version = sb. toString (); Editor editor = spf. edit (); editor. putString ("contact_version", md5Version); editor. commit (); return md5Version;} catch (NoSuchAlgorithmException e) {e. printStackTrace ();} return null ;}
/*** Determines whether an update address book has been returned. true indicates an update is returned. false indicates that no update is returned. */public Boolean isContactUpdate () {String oldVersion = spf. getString ("contact_version", "first"); String newVersion = stringToMd5 (getContactsVersion (); if (Log. isLoggable ("version", Log. DEBUG) {Log. d ("version", "old version ---" + oldVersion); Log. d ("version", "new version ---" + newVersion);} return (! NewVersion. equals (oldVersion ));}