标签: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 style blog io color ar os java sp
原文地址:http://www.cnblogs.com/lcchuguo/p/4081902.html