Android 查看通訊錄Contacts是否發生變化

來源:互聯網
上載者:User

標籤:android   style   blog   io   color   ar   os   java   sp   

目的:確定通訊錄是否發生變化

根據:參見ContactsContract.RawContacts類中的VERSION常量,該值是僅僅讀的,當通訊錄發生變化時,都會使該值變化

方法:version值是相應每條通訊錄資料的,假設有100條,則有100個該值,我說採用的推斷方法是這種

1、擷取全部version值,組成字串

2、因為該字串可能非常長,所以採用MD5變換短字串

3、與之前的字串比較,將新的儲存到SharedPreferences 

以下三段代碼則實現了查看通訊錄是否變化

/**     * 獲得通訊錄的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, 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();    }
 /**     * 將字串version轉換成MD5格式的     *      * @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;    }
 /**     * 推斷是不是有更新通訊錄 返回true表示有更新,返回false表示沒有更新     */    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));    }



Android 查看通訊錄Contacts是否發生變化

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.