对于系统手机的联系人、短信、通话记录的一些列的方法,着实需要总结下了
我公司最近在做跟这相关的项目,这个博客后续会完善这3个模块的工具类方法
1、查询contacts表获取contactId, 通过contact_id去获取data表中相应的数据
2、获取联系人头像的3种方式
4、通过contact_id获取photo_id
5、查询raw_contacts表中的一些需要信息,例如displayName、sortKey、rawContactId、contactId
7、添加联系人
Pycomparator
CharacterParser
ContactInfo
我公司最近在做跟这相关的项目,这个博客后续会完善这3个模块的工具类方法
1、查询contacts表获取contactId, 通过contact_id去获取data表中相应的数据
/**
* 通过contactId从data表中获取联系人信息 Uri uri =
* Uri.parse("content://com.android.contacts/contacts/#/data");
* 查询contacts表获取contactId, 通过contact_id去获取data表中相应的数据
*/
public static void getContactInfoFromDataByContactId(Context mContext) {
// 访问contacts表
Uri uri = Uri.parse("content://com.android.contacts/contacts");
ContentResolver resolver = mContext.getContentResolver();
// 获得contact_id属性
Cursor cursor = resolver.query(uri, new String[] { Data._ID }, null,
null, null);
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int contactId = cursor.getInt(0);
// 通过contact_id,去获取data表中对应的值
uri = Uri.parse("content://com.android.contacts/contacts/"
+ contactId + "/data");
Cursor cursor2 = resolver.query(uri, new String[] { Data.DATA1,
Data.DATA15, Data.MIMETYPE }, null, null, null); // data1存储各个记录的总数据,mimetype存放记录的类型,如电话、email等
while (cursor2.moveToNext()) {
String data = cursor2.getString(cursor2
.getColumnIndex("data1"));
byte[] photo = cursor2.getBlob(cursor2
.getColumnIndex("data15"));
if (cursor2.getString(cursor2.getColumnIndex("mimetype"))
.equals("vnd.android.cursor.item/name")) { // 如果是名字
Log.i("TAG", "name" + data);
} else if (cursor2.getString(
cursor2.getColumnIndex("mimetype")).equals(
"vnd.android.cursor.item/phone_v2")) { // 如果是电话
Log.i("TAG", "phone" + data);
}
else if (cursor2.getString(
cursor2.getColumnIndex("mimetype")).equals(
"vnd.android.cursor.item/photo")) { // 如果是电话
Log.i("TAG", "photo" + photo.length);
}
}
Log.i("TAG", "--------------------");
}
}
}
2、获取联系人头像的3种方式
/*************************************************************
* 1、获取联系人头像
* 通过contactId获取联系人头像 查询contacts表获取contactId,
* 通过contact_id去获取data表中相应的photo数据
*/
public static Bitmap getContactPhotoFromDataByContactId(Context mContext,
String contactId) {
Bitmap bitmap = null;
// 访问contacts表
Uri uri = Uri.parse("content://com.android.contacts/contacts/"
+ contactId + "/data");
Cursor cursor = mContext.getContentResolver().query(uri,
new String[] { Data.DATA15, Data.MIMETYPE }, null, null, null); // data1存储各个记录的总数据,mimetype存放记录的类型,如电话、email等
if (cursor != null && cursor.getCount() > 0) {
// 通过contact_id,去获取data表中对应的值
while (cursor.moveToNext()) {
byte[] photoByte = cursor.getBlob(cursor
.getColumnIndex("data15"));
if (cursor.getString(cursor.getColumnIndex("mimetype")).equals(
"vnd.android.cursor.item/photo")) { // 如果是电话
Log.i("TAG", "photo" + photoByte.length);
bitmap = BitmapFactory.decodeByteArray(photoByte, 0,
photoByte.length);
}
}
}
return bitmap;
}
/**2、获取联系人头像
* 通过contactId获取联系人头像
* openContactPhotoInputStream进行读取操作
*/
public static Bitmap getContactPhotoByOpenContactPhotoInputStream(
Context mContext, String contactId) {
Uri uri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI,
Long.parseLong(contactId));
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(mContext.getContentResolver(),
uri, false);
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
/**3、获取联系人头像
* 通过电话号码获取头像
* 通过电话号码获取contactId
* 如果2个contactId,都有相同的电话号码,这里的代码默认取第一个联系人的头像
* openContactPhotoInputStream进行读取操作
*/
public static Bitmap getContactPhotoDataPhoneFilter(Context mContext,String PhoneNumber){
Bitmap bitmap = null;
// 获得Uri
Uri uriNumber2Contacts = Uri.parse("content://com.android.contacts/"
+ "data/phones/filter/" + PhoneNumber);
// 查询Uri,返回数据集
Cursor cursorCantacts = mContext.getContentResolver().query(
uriNumber2Contacts,
null,
null,
null,
null);
if (cursorCantacts!=null && cursorCantacts.getCount()>0) {
if ( cursorCantacts.moveToFirst()) {
Long contactID = cursorCantacts.getLong(cursorCantacts.getColumnIndex("contact_id"));
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactID);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(mContext.getContentResolver(), uri);
return (bitmap = BitmapFactory.decodeStream(input));
}
}
return bitmap;
}
3、从contacts表中获取contactId、photoId、rawContactId值
public static void getSingleColumnsFromContactsTable(Context mContext,String contactId) {
// 访问contacts表
Uri uri = Uri.parse("content://com.android.contacts/contacts");
ContentResolver resolver = mContext.getContentResolver();
// 从contacts表中获取contactId、photoId、rawContactId
Cursor cursor = resolver.query(uri, new String[] { Data._ID,
CommonDataKinds.Photo.PHOTO_ID,CommonDataKinds.Phone.NAME_RAW_CONTACT_ID}, "_id=?", new String[]{contactId}, null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
int cursorContactId = cursor.getInt(0);
int photoId = cursor.getInt(cursor
.getColumnIndex(CommonDataKinds.Phone.PHOTO_ID));
int rawContactId = cursor.getInt(cursor
.getColumnIndex(CommonDataKinds.Phone.NAME_RAW_CONTACT_ID));
Log.i("TAG", "contactId:" + cursorContactId);
Log.i("TAG", "photoId:" + photoId);
Log.i("TAG", "rawContactId:" + rawContactId);
}
}
}
4、通过contact_id获取photo_id
/**
* 通过contactId获取头像photo_id
* Uri photoIdByContactId =
* Uri.parse("content://com.android.contacts/contacts/"+1+"/photo");
*/
public static void getRawContactIdByContactId(Context mContext) {
// 访问contacts表
Uri uri = Uri.parse("content://com.android.contacts/contacts");
ContentResolver resolver = mContext.getContentResolver();
// 从contacts表中获取contactId
Cursor cursor = resolver.query(uri, new String[] { Data._ID }, null,
null, null);
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int contactId = cursor.getInt(0);
Cursor query = resolver
.query(Uri
.parse("content://com.android.contacts/contacts/"
+ contactId + "/photo"), null, null,
null, null);
if (query != null && query.getCount() > 0
&& query.moveToFirst()) {
int photoId = query.getInt(query
.getColumnIndex(Phone.PHOTO_ID));
Log.i("TAG", "contactId:" + contactId+ ",photoId:" + photoId);
}
}
}
}
5、查询raw_contacts表中的一些需要信息,例如displayName、sortKey、rawContactId、contactId
/**
* contactId为空的就是被删掉的联系人
* 查询raw_contacts表,去获取联系人的信息
*/
public static void getColumnsFromRawContactsTable(Context mContext) {
// 访问contacts表
Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
ContentResolver resolver = mContext.getContentResolver();
String[] projection = { Data._ID, CommonDataKinds.Phone.CONTACT_ID,
CommonDataKinds.Phone.DISPLAY_NAME,
CommonDataKinds.Phone.SORT_KEY_PRIMARY,"phonebook_label" };//sort_key
Cursor cursor = resolver.query(uri, projection, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int rawContactId = cursor.getInt(0);
int contactId = cursor.getInt(1);
String displayName = cursor.getString(2);
String sortKey = cursor.getString(3);
String phonebook_label = cursor.getString(4);
if (contactId!=0) {
Log.i("TAG", "rawContactId:" + rawContactId);
Log.i("TAG", "contactId:" + contactId);
Log.i("TAG", "displayName:" + displayName);
Log.i("TAG", "sortKey:" + sortKey);
Log.i("TAG", "sortKey:" + phonebook_label);
Log.i("TAG", "--------------");
}
}
}
}
6、根据电话号码获取联系人姓名
/**
* 根据电话号码获取联系人姓名
* 如果2个联系人有同样的号码,默认获取第一个
*/
public static void getContactNameByPhonNum(Context mContext, String phoneNum) {
ContentResolver resolver = mContext.getContentResolver();
Uri uri = Uri
.parse("content://com.android.contacts/data/phones/filter/"
+ phoneNum);
Cursor c = resolver.query(uri, new String[] { "display_name" }, null,
null, null);
if (c != null && c.getCount() > 0 && c.moveToFirst()) {
Log.i("TAG", "phoneNum:" + c.getString(0));
}
}
7、添加联系人
/**
* 添加联系人
* @param mContext
*/
public static boolean insertContact(Context mContext,String given_name, String mobile_number,
String work_email) {
ContentValues values = new ContentValues();
// 下面的操作会根据RawContacts表中已有的rawContactId使用情况自动生成新联系人的rawContactId
Uri rawContactUri = mContext.getContentResolver().insert(
RawContacts.CONTENT_URI, values);
long rawContactId = ContentUris.parseId(rawContactUri);
// 向data表插入姓名数据
if (given_name != "") {
values.clear();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
values.put(StructuredName.GIVEN_NAME, given_name);
mContext.getContentResolver().insert(ContactsContract.Data.CONTENT_URI,
values);
}
// 向data表插入电话数据
if (mobile_number != "") {
values.clear();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
values.put(Phone.NUMBER, mobile_number);
values.put(Phone.TYPE, Phone.TYPE_MOBILE);
mContext.getContentResolver().insert(ContactsContract.Data.CONTENT_URI,
values);
}
// 向data表插入Email数据
if (work_email != "") {
values.clear();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);
values.put(Email.DATA, work_email);
values.put(Email.TYPE, Email.TYPE_WORK);
mContext.getContentResolver().insert(ContactsContract.Data.CONTENT_URI,
values);
}
values.clear();
// 向data表插入头像数据
Bitmap sourceBitmap = BitmapFactory.decodeResource(mContext.getResources(),
R.drawable.ic_launcher);
final ByteArrayOutputStream os = new ByteArrayOutputStream();
// 将Bitmap压缩成PNG编码,质量为100%存储
sourceBitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
byte[] avatar = os.toByteArray();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE);
values.put(Photo.PHOTO, avatar);
mContext.getContentResolver().insert(ContactsContract.Data.CONTENT_URI,
values);
return true;
}
8、根据字母查询联系人、根据电话号码模糊查询
/**
* 根据名字中的某一个字进行模糊查询
* matcher.addURI(ContactsContract.AUTHORITY, "data/phones", PHONES);
* @param key
*/
public static void getFuzzyQueryByName(Context mContext, String key) {
StringBuilder sb = new StringBuilder();
ContentResolver cr = mContext.getContentResolver();
//display_name、data1
String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
Cursor cursor = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection,
ContactsContract.Contacts.DISPLAY_NAME + " like " + "'%" + key
+ "%'", null, null);
while (cursor.moveToNext()) {
String name = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String number = cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
sb.append(name + " (").append(number + ")").append("\r\n");
}
cursor.close();
if (!sb.toString().isEmpty()) {
Log.d("TAG", "查询联系人:\r\n" + sb.toString());
}
}
/**
* 根据电话号码进行模糊查询
*
*/
public static void getFuzzyByPhoneNum(Context mContext, String key) {
String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
Cursor cursor = mContext.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection,
ContactsContract.CommonDataKinds.Phone.NUMBER + " like " + "'%"
+ key + "%'",
null,
null);
if (cursor == null) {
return;
}
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
String name = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String number = cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i("TAG", "根据号码查联系人 name: " + name + "----" + " number:"
+ number + " \n"); // 这里提示
}
}
9、获取联系人,通过获取contactId,继而获取raw_contactId,继而获取联系人数据
/**
* 读取联系人 1、先读取contacts表,获取ContactsID;
*
* 2、再在raw_contacts表中根据ContactsID获取RawContactsID;
*
* 3、然后就可以在data表中根据RawContactsID获取该联系人的各数据了。
*/
public static void queryContactsByContactIdAndRawContactId(Context mContext) {
// 获取用来操作数据的类的对象,对联系人的基本操作都是使用这个对象
ContentResolver cr = mContext.getContentResolver();
// 查询contacts表的所有记录
Cursor contactCursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
if (contactCursor.getCount() > 0) {
// 游标初始指向查询结果的第一条记录的上方,执行moveToNext函数会判断
// 下一条记录是否存在,如果存在,指向下一条记录。否则,返回false。
while (contactCursor.moveToNext()) {
String rawContactId = "";
String id = contactCursor.getString(contactCursor
.getColumnIndex(ContactsContract.Contacts._ID));
Log.v("TAG", "id:"+id);
Cursor rawContactCur = cr.query(RawContacts.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Contactables.CONTACT_ID + "=?", new String[] { id }, null);
if (rawContactCur.moveToFirst()) {
rawContactId = rawContactCur.getString(rawContactCur
.getColumnIndex(RawContacts._ID));
Log.v("TAG", "rawContactId:"+rawContactId);
}
rawContactCur.close();
// 读取号码
if (Integer
.parseInt(contactCursor.getString(contactCursor
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// 根据查询RAW_CONTACT_ID查询该联系人的号码
Cursor phoneCur = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID
+ "=?",
new String[] { rawContactId }, null);
// 上面的ContactsContract.CommonDataKinds.Phone.CONTENT_URI
// 可以用下面的phoneUri代替
// phoneUri=Uri.parse("content://com.android.contacts/data/phones");
// 一个联系人可能有多个号码,需要遍历
while (phoneCur.moveToNext()) {
String number = phoneCur
.getString(phoneCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.v("TAG", "number:"+number);
}
phoneCur.close();
}
}
contactCursor.close();
}
}
10、删除、更新联系人
// 删除联系人
public static void deleteContact(Context mContext, long rawContactId) {
mContext.getContentResolver().delete(
ContentUris.withAppendedId(RawContacts.CONTENT_URI,
rawContactId), null, null);
}
/**
* 更新联系人
* @param mContext
* @param rawContactId
*
* 代码不严谨,
* 因为raw_contacts表中的contact_id列为0时候,说明这个联系人被删除了,
* 应该先通过raw_contactid 判断contact_id是否为0,如果不为0,在进行更新操作
* 可以直接在raw_contacts表中,也可以在contacts表中去判断都可
*/
public static void updataCotact(Context mContext, long rawContactId) {
ContentValues values = new ContentValues();
values.put(Phone.NUMBER, "13800138000");
values.put(Phone.TYPE, Phone.TYPE_MOBILE);
String where = ContactsContract.Data.RAW_CONTACT_ID + "=? AND "
+ ContactsContract.Data.MIMETYPE + "=?";
String[] selectionArgs = new String[] { String.valueOf(rawContactId),
Phone.CONTENT_ITEM_TYPE };
mContext.getContentResolver().update(ContactsContract.Data.CONTENT_URI,
values, where, selectionArgs);
}
11、通过content://com.android.contacts/data/phones方式获取联系人
这个方法有个问题,就是没有号码的联系人无法获取
ContactsManager
package com.example.testinsertcontacts;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.util.Log;
/**
* Created by Administrator on 2016/4/13.
*/
public class ContactsManager {
private static ContactsManager instance;
private static HashMap<Long, Boolean> isImportCalllog = new HashMap<Long, Boolean>();
private static Context context;
public static ContactsManager getInstance(Context c) {
context = c;
if (instance == null) {
instance = new ContactsManager();
}
return instance;
}
String[] contact_projection = {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.PHOTO_ID };
// 获取联系人的信息并排序
public byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
private String getSortKey(String sortKey) {
String key = sortKey.substring(0, 1).toUpperCase();
if (key.matches("[A-Z]")) {
return key;
}
return "#";
}
private boolean isChinese(char a) {
return String.valueOf(a).matches("[\u4E00-\u9FA5]");
}
public ArrayList<ContactInfo> getContactsFromInternal() {
ArrayList<String> contactPhones = new ArrayList<String>();
ContactInfo member = null;
ArrayList<ContactInfo> listsContacts = new ArrayList<ContactInfo>();
Uri uri = Uri.parse("content://com.android.contacts");
Uri dataUri = Uri.withAppendedPath(uri, "data");
Uri commonPhoneUri = Uri.withAppendedPath(dataUri, "phones");
Cursor cursor = null;
try {
long oldContactId = -1;
cursor = context.getContentResolver().query(commonPhoneUri,
contact_projection, null, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String name = cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String oldSortKey = cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY));
String newSortKey = oldSortKey;
if (isChinese(oldSortKey.charAt(0))) {
newSortKey = CharacterParser.getInstance().getSelling(
oldSortKey);
}
String sortKey = getSortKey(newSortKey);
long contactId = cursor
.getLong(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String number = cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (contactId == oldContactId) {
contactPhones.add(number);
member.setContactPhones(contactPhones);
continue;
} else {
member = new ContactInfo();
listsContacts.add(member);
contactPhones = new ArrayList<String>();
contactPhones.add(number);
}
int photoId = cursor
.getInt(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_ID));
if (photoId != 0) {
if (photoId != 0) {
Uri photoUri = Uri
.parse("content://com.android.contacts/contacts/"
+ contactId);
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(
context.getContentResolver(),
photoUri);
byte[] photoByte = null;
if (input != null) {
photoByte = toByteArray(input);
member.setPhoto(photoByte);
}
}
}
// 获取备注
String note = "";
String noteWhere = ContactsContract.Data.CONTACT_ID
+ " = ? AND " + ContactsContract.Data.MIMETYPE
+ " = ?";
String[] noteWhereParams = new String[] {
"" + contactId,
ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE };
Cursor noteCur = context.getContentResolver().query(
ContactsContract.Data.CONTENT_URI, null, noteWhere,
noteWhereParams, null);
if (noteCur.moveToFirst()) {
note = noteCur
.getString(noteCur
.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
}
noteCur.close();
Log.i("Safly", "name:" + name + ",sortKey:"
+ sortKey + ",contactId:" + contactId + ",number:"
+ number + ",note:" + note);
member.setSortKey(sortKey);
member.setContactPhones(contactPhones);
member.setName(name);
member.setContactId(contactId);
member.setRemark(note);
oldContactId = contactId;
}
}
if (listsContacts != null)
Collections.sort(listsContacts, new Pycomparator());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
return listsContacts;
}
}
Pycomparator
package com.example.testinsertcontacts;
import java.util.ArrayList;
import java.util.Comparator;
import android.text.TextUtils;
/**
* Created by Administrator on 2016/4/14.
*/
public class Pycomparator implements Comparator<ContactInfo> {
@Override
public int compare(ContactInfo contact1, ContactInfo contact2) {
String name1=contact1.getSortKey();
String name2=contact2.getSortKey();
if (TextUtils.isEmpty(name1)){
ArrayList<String> contactPhones= (ArrayList<String>) contact1.getPhones();
if (contactPhones!=null&&contactPhones.size()>0)
name1=contactPhones.get(0);
}
if (TextUtils.isEmpty(name2)){
ArrayList<String> contactPhones= (ArrayList<String>) contact2.getPhones();
if (contactPhones!=null&&contactPhones.size()>0){
name2=contactPhones.get(0);
}
}
if (!TextUtils.isEmpty(name1)&&!TextUtils.isEmpty(name2)){
boolean firstisChar=false;
boolean secondisChar=false;
if (((name1.charAt(0)>='a'&&name1.charAt(0)<='z'))||(name1.charAt(0)>='A'&&name1.charAt(0)<='Z'))
firstisChar=true;
if (((name2.charAt(0)>='a'&&name2.charAt(0)<='z'))||(name2.charAt(0)>='A'&&name2.charAt(0)<='Z'))
secondisChar=true;
if (firstisChar&&secondisChar){
return name1.compareToIgnoreCase(name2);
}else if (firstisChar&&!secondisChar){
return -1;
}else if (!firstisChar&&secondisChar){
return 1;
}else{
return name1.compareToIgnoreCase(name2);
}
}
return 0;
}
}
CharacterParser
package com.example.testinsertcontacts;
/**
* Created by Administrator on 2016/4/14.
*/
public class CharacterParser {
private static int[] pyvalue = new int[] {-20319, -20317, -20304, -20295, -20292, -20283, -20265, -20257, -20242, -20230, -20051, -20036, -20032,
-20026, -20002, -19990, -19986, -19982, -19976, -19805, -19784, -19775, -19774, -19763, -19756, -19751, -19746, -19741, -19739, -19728,
-19725, -19715, -19540, -19531, -19525, -19515, -19500, -19484, -19479, -19467, -19289, -19288, -19281, -19275, -19270, -19263, -19261,
-19249, -19243, -19242, -19238, -19235, -19227, -19224, -19218, -19212, -19038, -19023, -19018, -19006, -19003, -18996, -18977, -18961,
-18952, -18783, -18774, -18773, -18763, -18756, -18741, -18735, -18731, -18722, -18710, -18697, -18696, -18526, -18518, -18501, -18490,
-18478, -18463, -18448, -18447, -18446, -18239, -18237, -18231, -18220, -18211, -18201, -18184, -18183, -18181, -18012, -17997, -17988,
-17970, -17964, -17961, -17950, -17947, -17931, -17928, -17922, -17759, -17752, -17733, -17730, -17721, -17703, -17701, -17697, -17692,
-17683, -17676, -17496, -17487, -17482, -17468, -17454, -17433, -17427, -17417, -17202, -17185, -16983, -16970, -16942, -16915, -16733,
-16708, -16706, -16689, -16664, -16657, -16647, -16474, -16470, -16465, -16459, -16452, -16448, -16433, -16429, -16427, -16423, -16419,
-16412, -16407, -16403, -16401, -16393, -16220, -16216, -16212, -16205, -16202, -16187, -16180, -16171, -16169, -16158, -16155, -15959,
-15958, -15944, -15933, -15920, -15915, -15903, -15889, -15878, -15707, -15701, -15681, -15667, -15661, -15659, -15652, -15640, -15631,
-15625, -15454, -15448, -15436, -15435, -15419, -15416, -15408, -15394, -15385, -15377, -15375, -15369, -15363, -15362, -15183, -15180,
-15165, -15158, -15153, -15150, -15149, -15144, -15143, -15141, -15140, -15139, -15128, -15121, -15119, -15117, -15110, -15109, -14941,
-14937, -14933, -14930, -14929, -14928, -14926, -14922, -14921, -14914, -14908, -14902, -14894, -14889, -14882, -14873, -14871, -14857,
-14678, -14674, -14670, -14668, -14663, -14654, -14645, -14630, -14594, -14429, -14407, -14399, -14384, -14379, -14368, -14355, -14353,
-14345, -14170, -14159, -14151, -14149, -14145, -14140, -14137, -14135, -14125, -14123, -14122, -14112, -14109, -14099, -14097, -14094,
-14092, -14090, -14087, -14083, -13917, -13914, -13910, -13907, -13906, -13905, -13896, -13894, -13878, -13870, -13859, -13847, -13831,
-13658, -13611, -13601, -13406, -13404, -13400, -13398, -13395, -13391, -13387, -13383, -13367, -13359, -13356, -13343, -13340, -13329,
-13326, -13318, -13147, -13138, -13120, -13107, -13096, -13095, -13091, -13076, -13068, -13063, -13060, -12888, -12875, -12871, -12860,
-12858, -12852, -12849, -12838, -12831, -12829, -12812, -12802, -12607, -12597, -12594, -12585, -12556, -12359, -12346, -12320, -12300,
-12120, -12099, -12089, -12074, -12067, -12058, -12039, -11867, -11861, -11847, -11831, -11798, -11781, -11604, -11589, -11536, -11358,
-11340, -11339, -11324, -11303, -11097, -11077, -11067, -11055, -11052, -11045, -11041, -11038, -11024, -11020, -11019, -11018, -11014,
-10838, -10832, -10815, -10800, -10790, -10780, -10764, -10587, -10544, -10533, -10519, -10331, -10329, -10328, -10322, -10315, -10309,
-10307, -10296, -10281, -10274, -10270, -10262, -10260, -10256, -10254};
public static String[] pystr = new String[] {"a", "ai", "an", "ang", "ao", "ba", "bai", "ban", "bang", "bao", "bei", "ben", "beng", "bi", "bian",
"biao", "bie", "bin", "bing", "bo", "bu", "ca", "cai", "can", "cang", "cao", "ce", "ceng", "cha", "chai", "chan", "chang", "chao", "che",
"chen", "cheng", "chi", "chong", "chou", "chu", "chuai", "chuan", "chuang", "chui", "chun", "chuo", "ci", "cong", "cou", "cu", "cuan",
"cui", "cun", "cuo", "da", "dai", "dan", "dang", "dao", "de", "deng", "di", "dian", "diao", "die", "ding", "diu", "dong", "dou", "du",
"duan", "dui", "dun", "duo", "e", "en", "er", "fa", "fan", "fang", "fei", "fen", "feng", "fo", "fou", "fu", "ga", "gai", "gan", "gang",
"gao", "ge", "gei", "gen", "geng", "gong", "gou", "gu", "gua", "guai", "guan", "guang", "gui", "gun", "guo", "ha", "hai", "han", "hang",
"hao", "he", "hei", "hen", "heng", "hong", "hou", "hu", "hua", "huai", "huan", "huang", "hui", "hun", "huo", "ji", "jia", "jian",
"jiang", "jiao", "jie", "jin", "jing", "jiong", "jiu", "ju", "juan", "jue", "jun", "ka", "kai", "kan", "kang", "kao", "ke", "ken",
"keng", "kong", "kou", "ku", "kua", "kuai", "kuan", "kuang", "kui", "kun", "kuo", "la", "lai", "lan", "lang", "lao", "le", "lei", "leng",
"li", "lia", "lian", "liang", "liao", "lie", "lin", "ling", "liu", "long", "lou", "lu", "lv", "luan", "lue", "lun", "luo", "ma", "mai",
"man", "mang", "mao", "me", "mei", "men", "meng", "mi", "mian", "miao", "mie", "min", "ming", "miu", "mo", "mou", "mu", "na", "nai",
"nan", "nang", "nao", "ne", "nei", "nen", "neng", "ni", "nian", "niang", "niao", "nie", "nin", "ning", "niu", "nong", "nu", "nv", "nuan",
"nue", "nuo", "o", "ou", "pa", "pai", "pan", "pang", "pao", "pei", "pen", "peng", "pi", "pian", "piao", "pie", "pin", "ping", "po", "pu",
"qi", "qia", "qian", "qiang", "qiao", "qie", "qin", "qing", "qiong", "qiu", "qu", "quan", "que", "qun", "ran", "rang", "rao", "re",
"ren", "reng", "ri", "rong", "rou", "ru", "ruan", "rui", "run", "ruo", "sa", "sai", "san", "sang", "sao", "se", "sen", "seng", "sha",
"shai", "shan", "shang", "shao", "she", "shen", "sheng", "shi", "shou", "shu", "shua", "shuai", "shuan", "shuang", "shui", "shun",
"shuo", "si", "song", "sou", "su", "suan", "sui", "sun", "suo", "ta", "tai", "tan", "tang", "tao", "te", "teng", "ti", "tian", "tiao",
"tie", "ting", "tong", "tou", "tu", "tuan", "tui", "tun", "tuo", "wa", "wai", "wan", "wang", "wei", "wen", "weng", "wo", "wu", "xi",
"xia", "xian", "xiang", "xiao", "xie", "xin", "xing", "xiong", "xiu", "xu", "xuan", "xue", "xun", "ya", "yan", "yang", "yao", "ye", "yi",
"yin", "ying", "yo", "yong", "you", "yu", "yuan", "yue", "yun", "za", "zai", "zan", "zang", "zao", "ze", "zei", "zen", "zeng", "zha",
"zhai", "zhan", "zhang", "zhao", "zhe", "zhen", "zheng", "zhi", "zhong", "zhou", "zhu", "zhua", "zhuai", "zhuan", "zhuang", "zhui",
"zhun", "zhuo", "zi", "zong", "zou", "zu", "zuan", "zui", "zun", "zuo"};
private String resource;
private static CharacterParser characterParser = new CharacterParser();
public static CharacterParser getInstance() {
return characterParser;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
/** * 汉字转成ASCII码 * * @param chs * @return */
private int getChsAscii(String chs) {
int asc = 0;
try {
byte[] bytes = chs.getBytes("gb2312");
if (bytes == null || bytes.length > 2 || bytes.length <= 0) {
throw new RuntimeException("illegal resource string");
}
if (bytes.length == 1) {
asc = bytes[0];
}
if (bytes.length == 2) {
int hightByte = 256 + bytes[0];
int lowByte = 256 + bytes[1];
asc = (256 * hightByte + lowByte) - 256 * 256;
}
} catch (Exception e) {
System.out.println("ERROR:ChineseSpelling.class-getChsAscii(String chs)" + e);
}
return asc;
}
/** * 单字解析 * * @param str * @return */
public String convert(String str) {
String result = null;
int ascii = getChsAscii(str);
if (ascii > 0 && ascii < 160) {
result = String.valueOf((char) ascii);
} else {
for (int i = (pyvalue.length - 1); i >= 0; i--) {
if (pyvalue[i] <= ascii) {
result = pystr[i];
break;
}
}
}
return result;
}
/** * 词组解析 * * @param chs * @return */
public String getSelling(String chs) {
String key, value;
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < chs.length(); i++) {
key = chs.substring(i, i + 1);
if (key.getBytes().length >= 2) {
value = convert(key);
if (value == null) {
value = "unknown";
}
} else {
value = key;
}
buffer.append(value);
}
return buffer.toString();
}
public String getSpelling() {
return this.getSelling(this.getResource());
}
}
ContactInfo
package com.example.testinsertcontacts;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by dandy on 2016/6/7.
*/
public class ContactInfo implements Serializable{
private long contactId;
private String name;
private String remark;
private List<String> phones = new ArrayList<String>();
private String sortKey;//用于排序
private boolean isCheck;
private byte[] photoByte;
public ContactInfo(long contactId,byte[] bytes,String name, String remark, List<String> phones, String sortKey, boolean isCheck) {
this.contactId = contactId;
this.photoByte = bytes;
this.name = name;
this.remark = remark;
this.phones = phones;
this.sortKey = sortKey;
this.isCheck = isCheck;
}
public byte[] getPhoto() {
return photoByte;
}
public void setPhoto(byte[] photoByte) {
this.photoByte = photoByte;
}
public ContactInfo() {
}
public long getContactId() {
return contactId;
}
public void setContactId(long contactId) {
this.contactId = contactId;
}
public List<String> getPhones() {
return phones;
}
public void addPhone(String phone){
phones.add(phone);
}
public void setContactPhones(ArrayList<String> contactPhones) {
this.phones = contactPhones;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setSortKey(String sortKey) {
this.sortKey = sortKey;
}
public String getSortKey() {
return sortKey;
}
public boolean isCheck() {
return isCheck;
}
public void setIsCheck(boolean isCheck) {
this.isCheck = isCheck;
}
}
12、测试随机插入联系人数据、全部删除联系人
findViewById(R.id.wushi).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for (int i = 0; i < 50; i++) {
Uri url = Uri
.parse("content://com.android.contacts/raw_contacts");
ContentValues values = new ContentValues();
Uri newUri = getContentResolver().insert(url, values);
long raw_contact_id = ContentUris.parseId(newUri);
url = Uri.parse("content://com.android.contacts/data");
values.clear();
values.put("mimetype", "vnd.android.cursor.item/phone_v2");
values.put("raw_contact_id", raw_contact_id);
values.put("data1", getRandomPhone(11));
getContentResolver().insert(url, values);
values.clear();
values.put("mimetype", "vnd.android.cursor.item/name");
values.put("raw_contact_id", raw_contact_id);
values.put("data1", getRandomString(3));
getContentResolver().insert(url, values);
values.clear();
}
}
});
findViewById(R.id.dele).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = Uri
.parse("content://com.android.contacts/raw_contacts");
ContentResolver resolver = getContentResolver();
String[] projection = { Data._ID,
CommonDataKinds.Phone.CONTACT_ID,
CommonDataKinds.Phone.DISPLAY_NAME,
CommonDataKinds.Phone.SORT_KEY_PRIMARY,
"phonebook_label" };// sort_key
Cursor cursor = resolver.query(uri, projection, null, null,
null);
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
getContentResolver().delete(
ContentUris.withAppendedId(
RawContacts.CONTENT_URI,
cursor.getInt(0)), null, null);
}
}
}
});
public String getRandomPhone(int length) { // length表示生成字符串的长度
String base = "123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
public String getRandomString(int length) { // length表示生成字符串的长度
String base = "abcdefghijklmnopqrstuvwxyz";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
13、获取联系人通话记录--插入通话记录
ContactsManager
package com.godinsec.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
public class ContactsManager {
private String TAG = "ContactsManager";
private static ContactsManager instance;
private static Context context;
public static ContactsManager getInstance(Context c) {
context = c;
if (instance == null) {
instance = new ContactsManager();
}
return instance;
}
String[] contact_projection = {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Note.NOTE,
ContactsContract.CommonDataKinds.Phone.PHOTO_ID};
/**
* 获取系统联系人的信息并排序
*/
public ArrayList<ContactInfo> getContacts() {
ArrayList<ContactInfo> listsContacts = new ArrayList<ContactInfo>();
ContactInfo member = null;
ArrayList<String> contactPhones = new ArrayList<String>();
Cursor cursor = null;
try {
long oldContactId = -1;
Uri uri = Uri.parse("content://com.android.contacts");
Uri dataUri = Uri.withAppendedPath(uri, "data");
Uri commonPhoneUri = Uri.withAppendedPath(dataUri, "phones");
cursor = context.getContentResolver().query(commonPhoneUri, contact_projection, null, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String oldSortKey = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY));
String newSortKey = oldSortKey;
if (isChinese(oldSortKey.charAt(0))) {
newSortKey = CharacterParser.getInstance().getSelling(oldSortKey);
}
String sortKey = getSortKey(newSortKey);
long contactId = cursor.getLong(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).trim().replace(" ", "");
if (contactId == oldContactId) {
contactPhones.add(number);
member.setContactPhones(contactPhones);
continue;
} else {
member = new ContactInfo();
contactPhones = new ArrayList<String>();
contactPhones.add(number);
}
int photoId = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_ID));
/** 头像*/
if (photoId != 0) {
Uri photoUri = Uri.parse("content://com.android.contacts/contacts/" + contactId);
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(context.getContentResolver(), photoUri);
byte[] photoByte = null;
if (input != null) {
photoByte = toByteArray(input);
member.setPhoto(photoByte);
}
}
member.setSortKey(sortKey);
member.setContactPhones(contactPhones);
member.setName(name.trim().replace(" ", ""));
member.setContactId(contactId);
member.setContactFlag(System.nanoTime());
listsContacts.add(member);
oldContactId = contactId;
}
}
if (listsContacts != null) {
Collections.sort(listsContacts, new Pycomparator());
}
} catch (Exception e) {
Log.i("ContactsManager", "Exception");
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
return listsContacts;
}
public byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
private String getSortKey(String sortKey) {
String key = sortKey.substring(0, 1).toUpperCase();
if (key.matches("[A-Z]")) {
return key;
}
return "#";
}
private boolean isChinese(char a) {
return String.valueOf(a).matches("[\u4E00-\u9FA5]");
}
public ArrayList<CalllogItem> getCalllogFromExternal() {
ArrayList<ContactInfo> listsContact = getContacts();
if (listsContact == null || listsContact.size() == 0) {
return null;
}
Cursor cursor = null;
ArrayList<CalllogItem> listsCalllog = new ArrayList<CalllogItem>();
try {
String[] projection = {
CallLog.Calls._ID,
CallLog.Calls.NUMBER,
CallLog.Calls.DATE,
CallLog.Calls.DURATION,
CallLog.Calls.TYPE,
CallLog.Calls.CACHED_NUMBER_TYPE,
CallLog.Calls.CACHED_NUMBER_LABEL
};
String selection = CallLog.Calls.NUMBER + "=?";
String[] selectionArgs;
for (int i = 0; i < listsContact.size(); i++) {
if (listsContact.get(i).getPhones().size() == 1) {
String num = listsContact.get(i).getPhones().get(0).replace(" ", "");
String formatNum = PhoneNumberUtils.formatNumber(num);
selectionArgs = new String[]{formatNum};
cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI, projection, selection, selectionArgs, null);
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
CalllogItem item = new CalllogItem();
long _id = cursor.getLong(cursor.getColumnIndex(CallLog.Calls._ID));
String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
long date = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
long duration = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DURATION));
int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
String name = listsContact.get(i).getName();
int number_type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.CACHED_NUMBER_TYPE));
String number_label = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NUMBER_LABEL));
item.set_id(_id);
item.setNumber(number);
item.setDate(date);
item.setDuration(duration);
item.setType(type);
item.setName(name);
item.setNumber_type(number_type);
item.setNumber_label(number_label);
listsCalllog.add(item);
}
}
} else if (listsContact.get(i).getPhones().size() > 1) {
for (int j = 0; j < listsContact.get(i).getPhones().size(); j++) {
selectionArgs = new String[]{
listsContact.get(i).getPhones().get(j).replace(" ", "")};
cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI, projection, selection, selectionArgs, null);
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
CalllogItem item = new CalllogItem();
long _id = cursor.getLong(cursor.getColumnIndex(CallLog.Calls._ID));
String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
long date = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
long duration = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DURATION));
int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
String name = listsContact.get(i).getName();
int number_type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.CACHED_NUMBER_TYPE));
String number_label = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NUMBER_LABEL));
item.set_id(_id);
item.setNumber(number);
item.setDate(date);
item.setDuration(duration);
item.setType(type);
item.setName(name);
item.setNumber_type(number_type);
item.setNumber_label(number_label);
listsCalllog.add(item);
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
return listsCalllog;
}
public void insertCalllogIntoInternal() {
ArrayList<CalllogItem> listsCalllog = getCalllogFromExternal();
if (listsCalllog == null || listsCalllog.size() == 0) {
return;
}
ContentValues values = new ContentValues();
for (int i = 0; i < listsCalllog.size(); i++) {
if (values.size() != 0) {
values.clear();
}
values.put(CallLog.Calls.NUMBER, listsCalllog.get(i).getNumber());
values.put(CallLog.Calls.DATE, listsCalllog.get(i).getDate());
values.put(CallLog.Calls.DURATION, listsCalllog.get(i).getDuration());
values.put(CallLog.Calls.TYPE, listsCalllog.get(i).getType());
values.put(CallLog.Calls.NEW, listsCalllog.get(i).getIsnew());
values.put(CallLog.Calls.CACHED_NAME, listsCalllog.get(i).getName());
values.put(CallLog.Calls.CACHED_NUMBER_TYPE, listsCalllog.get(i).getNumber_type());
values.put(CallLog.Calls.CACHED_NUMBER_LABEL, listsCalllog.get(i).getNumber_label());
context.getContentResolver().insert(CallLog.Calls.CONTENT_URI, values);
}
}
}
CharacterParser
package com.godinsec.db;
/**
* Created by Administrator on 2016/4/14.
*/
public class CharacterParser {
private static int[] pyvalue = new int[] {-20319, -20317, -20304, -20295, -20292, -20283, -20265, -20257, -20242, -20230, -20051, -20036, -20032,
-20026, -20002, -19990, -19986, -19982, -19976, -19805, -19784, -19775, -19774, -19763, -19756, -19751, -19746, -19741, -19739, -19728,
-19725, -19715, -19540, -19531, -19525, -19515, -19500, -19484, -19479, -19467, -19289, -19288, -19281, -19275, -19270, -19263, -19261,
-19249, -19243, -19242, -19238, -19235, -19227, -19224, -19218, -19212, -19038, -19023, -19018, -19006, -19003, -18996, -18977, -18961,
-18952, -18783, -18774, -18773, -18763, -18756, -18741, -18735, -18731, -18722, -18710, -18697, -18696, -18526, -18518, -18501, -18490,
-18478, -18463, -18448, -18447, -18446, -18239, -18237, -18231, -18220, -18211, -18201, -18184, -18183, -18181, -18012, -17997, -17988,
-17970, -17964, -17961, -17950, -17947, -17931, -17928, -17922, -17759, -17752, -17733, -17730, -17721, -17703, -17701, -17697, -17692,
-17683, -17676, -17496, -17487, -17482, -17468, -17454, -17433, -17427, -17417, -17202, -17185, -16983, -16970, -16942, -16915, -16733,
-16708, -16706, -16689, -16664, -16657, -16647, -16474, -16470, -16465, -16459, -16452, -16448, -16433, -16429, -16427, -16423, -16419,
-16412, -16407, -16403, -16401, -16393, -16220, -16216, -16212, -16205, -16202, -16187, -16180, -16171, -16169, -16158, -16155, -15959,
-15958, -15944, -15933, -15920, -15915, -15903, -15889, -15878, -15707, -15701, -15681, -15667, -15661, -15659, -15652, -15640, -15631,
-15625, -15454, -15448, -15436, -15435, -15419, -15416, -15408, -15394, -15385, -15377, -15375, -15369, -15363, -15362, -15183, -15180,
-15165, -15158, -15153, -15150, -15149, -15144, -15143, -15141, -15140, -15139, -15128, -15121, -15119, -15117, -15110, -15109, -14941,
-14937, -14933, -14930, -14929, -14928, -14926, -14922, -14921, -14914, -14908, -14902, -14894, -14889, -14882, -14873, -14871, -14857,
-14678, -14674, -14670, -14668, -14663, -14654, -14645, -14630, -14594, -14429, -14407, -14399, -14384, -14379, -14368, -14355, -14353,
-14345, -14170, -14159, -14151, -14149, -14145, -14140, -14137, -14135, -14125, -14123, -14122, -14112, -14109, -14099, -14097, -14094,
-14092, -14090, -14087, -14083, -13917, -13914, -13910, -13907, -13906, -13905, -13896, -13894, -13878, -13870, -13859, -13847, -13831,
-13658, -13611, -13601, -13406, -13404, -13400, -13398, -13395, -13391, -13387, -13383, -13367, -13359, -13356, -13343, -13340, -13329,
-13326, -13318, -13147, -13138, -13120, -13107, -13096, -13095, -13091, -13076, -13068, -13063, -13060, -12888, -12875, -12871, -12860,
-12858, -12852, -12849, -12838, -12831, -12829, -12812, -12802, -12607, -12597, -12594, -12585, -12556, -12359, -12346, -12320, -12300,
-12120, -12099, -12089, -12074, -12067, -12058, -12039, -11867, -11861, -11847, -11831, -11798, -11781, -11604, -11589, -11536, -11358,
-11340, -11339, -11324, -11303, -11097, -11077, -11067, -11055, -11052, -11045, -11041, -11038, -11024, -11020, -11019, -11018, -11014,
-10838, -10832, -10815, -10800, -10790, -10780, -10764, -10587, -10544, -10533, -10519, -10331, -10329, -10328, -10322, -10315, -10309,
-10307, -10296, -10281, -10274, -10270, -10262, -10260, -10256, -10254};
public static String[] pystr = new String[] {"a", "ai", "an", "ang", "ao", "ba", "bai", "ban", "bang", "bao", "bei", "ben", "beng", "bi", "bian",
"biao", "bie", "bin", "bing", "bo", "bu", "ca", "cai", "can", "cang", "cao", "ce", "ceng", "cha", "chai", "chan", "chang", "chao", "che",
"chen", "cheng", "chi", "chong", "chou", "chu", "chuai", "chuan", "chuang", "chui", "chun", "chuo", "ci", "cong", "cou", "cu", "cuan",
"cui", "cun", "cuo", "da", "dai", "dan", "dang", "dao", "de", "deng", "di", "dian", "diao", "die", "ding", "diu", "dong", "dou", "du",
"duan", "dui", "dun", "duo", "e", "en", "er", "fa", "fan", "fang", "fei", "fen", "feng", "fo", "fou", "fu", "ga", "gai", "gan", "gang",
"gao", "ge", "gei", "gen", "geng", "gong", "gou", "gu", "gua", "guai", "guan", "guang", "gui", "gun", "guo", "ha", "hai", "han", "hang",
"hao", "he", "hei", "hen", "heng", "hong", "hou", "hu", "hua", "huai", "huan", "huang", "hui", "hun", "huo", "ji", "jia", "jian",
"jiang", "jiao", "jie", "jin", "jing", "jiong", "jiu", "ju", "juan", "jue", "jun", "ka", "kai", "kan", "kang", "kao", "ke", "ken",
"keng", "kong", "kou", "ku", "kua", "kuai", "kuan", "kuang", "kui", "kun", "kuo", "la", "lai", "lan", "lang", "lao", "le", "lei", "leng",
"li", "lia", "lian", "liang", "liao", "lie", "lin", "ling", "liu", "long", "lou", "lu", "lv", "luan", "lue", "lun", "luo", "ma", "mai",
"man", "mang", "mao", "me", "mei", "men", "meng", "mi", "mian", "miao", "mie", "min", "ming", "miu", "mo", "mou", "mu", "na", "nai",
"nan", "nang", "nao", "ne", "nei", "nen", "neng", "ni", "nian", "niang", "niao", "nie", "nin", "ning", "niu", "nong", "nu", "nv", "nuan",
"nue", "nuo", "o", "ou", "pa", "pai", "pan", "pang", "pao", "pei", "pen", "peng", "pi", "pian", "piao", "pie", "pin", "ping", "po", "pu",
"qi", "qia", "qian", "qiang", "qiao", "qie", "qin", "qing", "qiong", "qiu", "qu", "quan", "que", "qun", "ran", "rang", "rao", "re",
"ren", "reng", "ri", "rong", "rou", "ru", "ruan", "rui", "run", "ruo", "sa", "sai", "san", "sang", "sao", "se", "sen", "seng", "sha",
"shai", "shan", "shang", "shao", "she", "shen", "sheng", "shi", "shou", "shu", "shua", "shuai", "shuan", "shuang", "shui", "shun",
"shuo", "si", "song", "sou", "su", "suan", "sui", "sun", "suo", "ta", "tai", "tan", "tang", "tao", "te", "teng", "ti", "tian", "tiao",
"tie", "ting", "tong", "tou", "tu", "tuan", "tui", "tun", "tuo", "wa", "wai", "wan", "wang", "wei", "wen", "weng", "wo", "wu", "xi",
"xia", "xian", "xiang", "xiao", "xie", "xin", "xing", "xiong", "xiu", "xu", "xuan", "xue", "xun", "ya", "yan", "yang", "yao", "ye", "yi",
"yin", "ying", "yo", "yong", "you", "yu", "yuan", "yue", "yun", "za", "zai", "zan", "zang", "zao", "ze", "zei", "zen", "zeng", "zha",
"zhai", "zhan", "zhang", "zhao", "zhe", "zhen", "zheng", "zhi", "zhong", "zhou", "zhu", "zhua", "zhuai", "zhuan", "zhuang", "zhui",
"zhun", "zhuo", "zi", "zong", "zou", "zu", "zuan", "zui", "zun", "zuo"};
private String resource;
private static CharacterParser characterParser = new CharacterParser();
public static CharacterParser getInstance() {
return characterParser;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
/** * 汉字转成ASCII码 * * @param chs * @return */
private int getChsAscii(String chs) {
int asc = 0;
try {
byte[] bytes = chs.getBytes("gb2312");
if (bytes == null || bytes.length > 2 || bytes.length <= 0) {
throw new RuntimeException("illegal resource string");
}
if (bytes.length == 1) {
asc = bytes[0];
}
if (bytes.length == 2) {
int hightByte = 256 + bytes[0];
int lowByte = 256 + bytes[1];
asc = (256 * hightByte + lowByte) - 256 * 256;
}
} catch (Exception e) {
System.out.println("ERROR:ChineseSpelling.class-getChsAscii(String chs)" + e);
}
return asc;
}
/** * 单字解析 * * @param str * @return */
public String convert(String str) {
String result = null;
int ascii = getChsAscii(str);
if (ascii > 0 && ascii < 160) {
result = String.valueOf((char) ascii);
} else {
for (int i = (pyvalue.length - 1); i >= 0; i--) {
if (pyvalue[i] <= ascii) {
result = pystr[i];
break;
}
}
}
return result;
}
/** * 词组解析 * * @param chs * @return */
public String getSelling(String chs) {
String key, value;
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < chs.length(); i++) {
key = chs.substring(i, i + 1);
if (key.getBytes().length >= 2) {
value = convert(key);
if (value == null) {
value = "unknown";
}
} else {
value = key;
}
buffer.append(value);
}
return buffer.toString();
}
public String getSpelling() {
return this.getSelling(this.getResource());
}
}
Pycomparator
package com.godinsec.db;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.Comparator;
public class Pycomparator implements Comparator<ContactInfo> {
@Override
public int compare(ContactInfo contact1, ContactInfo contact2) {
String name1 = contact1.getSortKey();
String name2 = contact2.getSortKey();
if (TextUtils.isEmpty(name1)) {
ArrayList<String> contactPhones = (ArrayList<String>) contact1.getPhones();
if (contactPhones != null && contactPhones.size() > 0)
name1 = contactPhones.get(0);
}
if (TextUtils.isEmpty(name2)) {
ArrayList<String> contactPhones = (ArrayList<String>) contact2.getPhones();
if (contactPhones != null && contactPhones.size() > 0) {
name2 = contactPhones.get(0);
}
}
if (!TextUtils.isEmpty(name1) && !TextUtils.isEmpty(name2)) {
boolean firstisChar = false;
boolean secondisChar = false;
if (((name1.charAt(0) >= 'a' && name1.charAt(0) <= 'z')) || (name1.charAt(0) >= 'A' && name1.charAt(0) <= 'Z'))
firstisChar = true;
if (((name2.charAt(0) >= 'a' && name2.charAt(0) <= 'z')) || (name2.charAt(0) >= 'A' && name2.charAt(0) <= 'Z'))
secondisChar = true;
if (firstisChar && secondisChar) {
return name1.compareToIgnoreCase(name2);
} else if (firstisChar && !secondisChar) {
return -1;
} else if (!firstisChar && secondisChar) {
return 1;
} else {
return name1.compareToIgnoreCase(name2);
}
}
return 0;
}
}
ContactInfo
package com.godinsec.db;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class ContactInfo implements Serializable {
private static final long serialVersionUID = -7060210544600464481L;
private long contactFlag;
private long contactId;
private String name;
private List<String> phones = new ArrayList<>();
private String sortKey;//用于排序
private byte[] photoByte;
public void setContactFlag(long contactFlag) {
this.contactFlag = contactFlag;
}
public void setPhoto(byte[] photoByte) {
this.photoByte = photoByte;
}
public ContactInfo() {
}
public void setContactId(long contactId) {
this.contactId = contactId;
}
public List<String> getPhones() {
return phones;
}
public void setContactPhones(ArrayList<String> contactPhones) {
this.phones = contactPhones;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setSortKey(String sortKey) {
this.sortKey = sortKey;
}
public String getSortKey() {
return sortKey;
}
@Override
public String toString() {
return "ContactInfo{" +
"contactFlag=" + contactFlag +
", contactId=" + contactId +
", name='" + name + '\'' +
", phones=" + phones +
'}';
}
}
CalllogItem
package com.godinsec.db;
/**
* Created by Administrator on 2016/5/13.
*/
public class CalllogItem {
private long _id;
private String number;
private long date;//啥时候打的
private long duration;//打了多久
private int type;//来电类型
private boolean isnew;//是否已经查看 true未看,false已看
private String name;
private int number_type;//电话是home还是work
private String number_label;//
public void set_id(long _id) {
this._id = _id;
}
public void setDate(long date) {
this.date = date;
}
public void setDuration(long duration) {
this.duration = duration;
}
public void setIsnew(boolean isnew) {
this.isnew = isnew;
}
public void setName(String name) {
this.name = name;
}
public void setNumber(String number) {
this.number = number;
}
public void setNumber_label(String number_label) {
this.number_label = number_label;
}
public void setNumber_type(int number_type) {
this.number_type = number_type;
}
public void setType(int type) {
this.type = type;
}
public int getNumber_type() {
return number_type;
}
public int getType() {
return type;
}
public long get_id() {
return _id;
}
public long getDate() {
return date;
}
public long getDuration() {
return duration;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
public String getNumber_label() {
return number_label;
}
public boolean getIsnew() {
return isnew;
}
@Override
public String toString() {
return "CalllogItem{" +
"_id=" + _id +
", number='" + number + '\'' +
", date=" + date +
", duration=" + duration +
", type=" + type +
", isnew=" + isnew +
", name='" + name + '\'' +
", number_type=" + number_type +
", number_label='" + number_label + '\'' +
'}';
}
}
package com.godinsec.db;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;
import java.util.ArrayList;
/**
* Created by Administrator on 2016/11/4.
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_contact);
ArrayList<CalllogItem> calls = ContactsManager.getInstance(this).getCalllogFromExternal();
for (CalllogItem calllogItem : calls){
Log.i("MainActivity","calllogItem------------"+calllogItem.toString());
}
ContactsManager.getInstance(this).insertCalllogIntoInternal();
}
}