宿主手機連絡人、通話記錄、簡訊工具類(不斷完善中。。。)

來源:互聯網
上載者:User

標籤:

對於系統手機的連絡人、簡訊、通話記錄的一些列的方法,著實需要總結下了
我公司最近在做跟這相關的項目,這個部落格後續會完善這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、rawContactIdCursor 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表中擷取contactIdCursor 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_keyCursor 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、data1String[] 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);}


宿主手機連絡人、通話記錄、簡訊工具類(不斷完善中。。。)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.