Host mobile phone contacts, call logs, SMS tool class (constantly improve ... )

Source: Internet
Author: User

for the system phone contacts, text messages, call records some of the methods of the column, really need to summarize the
My company has been doing this related projects recently, this blog will improve the 3 modules of the tool-class method

1, Query contacts table to get ContactID, through contact_id to get the data table in the corresponding information

/** * Get contact information from the data table via ContactID uri uri = * Uri.parse ("Content://com.android.contacts/contacts/#/data"); * Query Contacts table get ContactID, through contact_id to get the data table in the corresponding */public static void Getcontactinfofromdatabycontactid (Context Mcontext) {//Access contacts table URI URI = uri.parse ("content://com.android.contacts/contacts"); Contentresolver resolver = Mcontext.getcontentresolver ();//Get contact_id property 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);//through contact_id, go to get the corresponding value in the data table 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 stores the total data for each record, mimetype the type of record, such as phone, email, etc. 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 ")) {// If the name is LOG.I ("TAG", "name" + data);} else if (cursor2.getstring (Cursor2.getcolumnindex ("MimeType")). Equals ("Vnd.android.cursor.item/phone_v2")) {// If it is the phone log.i ("TAG", "phone" + data); else if (cursor2.getstring (Cursor2.getcolumnindex ("MimeType")). Equals ("Vnd.android.cursor.item/photo")) {// If it is the phone log.i ("TAG", "photo" + Photo.length);}} LOG.I ("TAG", "--------------------");}}}

2.3 ways to get a contact avatar

/************************************************************* * 1, get contact Avatar * Get contact Avatar via ContactID Query the Contacts table for ContactID, * to obtain the corresponding photo data in the data table */public static Bitmap Getcontactphotofromdatabycontactid ( Context mcontext,string contactId) {Bitmap Bitmap = null;//access Contacts table 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 stores the total data for each record, mimetype the type of record, such as phone, email, etc. if (cursor! = NULL && cursor.getcount () > 0) {//through contact_id, To get the corresponding value in the data table while (Cursor.movetonext ()) {byte[] Photobyte = Cursor.getblob (Cursor.getcolumnindex ("Data15")); if ( Cursor.getstring (Cursor.getcolumnindex ("MimeType")). Equals ("Vnd.android.cursor.item/photo")) {//If it is a telephone log.i ("TAG "," photo "+ photobyte.length); bitmap = Bitmapfactory.decodebytearray (Photobyte, 0,photobyte.length);}}} return bitmap;} /**2, get contact Avatar * Get contact Avatar by ContactID * opencontactphOtoinputstream for read operations */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, get contact picture * Get avatar by phone number * Get ContactID by phone number * If 2 contactid have the same phone number, the code here defaults to the first contact's avatar * Opencontactphotoinputstream for read operations */public static Bitmap Getcontactphotodataphonefilter (Context mcontext,string  PhoneNumber) {Bitmap Bitmap = null; Get uri uri urinumber2contacts = uri.parse ("content://com.android.contacts/" + "data/phones/filter/" + PhoneNumber)   ; Query URI, return dataset Cursor cursorcantacts = Mcontext.getcontentresolver (). query (urinumber2contacts, NULL, NU    ll, NULL, NULL); if (Cursorcantacts!=null && CursorcantaCts.getcount () >0) {if (Cursorcantacts.movetofirst ()) {Long ContactID = Cursorcantacts.getlong (cursorcantacts.ge  Tcolumnindex ("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. Get ContactID, photoid, Rawcontactid values from the Contacts table

public static void Getsinglecolumnsfromcontactstable (Context mcontext,string contactId) {//Access contacts table URI URI = Uri.parse (" Content://com.android.contacts/contacts "); Contentresolver resolver = Mcontext.getcontentresolver ();//Get ContactID, PhotoID, rawcontactidcursor from the Contacts table 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.m Ovetofirst ()) {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. Get photo_id through contact_id

/** * ContactID get Avatar photo_id * Uri photoidbycontactid = * Uri.parse ("content://com.android.contacts/contacts/" +1+ "/ Photo "); */public static void Getrawcontactidbycontactid (Context mcontext) {//Access contacts table URI URI = Uri.parse ("content:// Com.android.contacts/contacts "); Contentresolver resolver = Mcontext.getcontentresolver ();//get contactidcursor cursor = Resolver.query from the Contacts table (URI, New string[] {data._id}, null,null, null), if (cursor! = NULL && cursor.getcount () > 0) {while (Cursor.moveton Ext ()) {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.getin T (Query.getcolumnindex (phone.photo_id)); LOG.I ("TAG", "contactId:" + contactid+ ", photoid:" + photoid);}}}


5, Query the Raw_contacts table of some needs information, such as DisplayName, SortKey, Rawcontactid, contactId

/** * ContactID is empty is the deleted contact * Query the raw_contacts table to get contact information */public static void Getcolumnsfromrawcontactstable (Context Mcontext) {//Access contacts table 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. Get contact name by phone number

/** * Get contact name by phone number * If 2 contacts have the same number, the default gets the first */public static void Getcontactnamebyphonnum (Context mcontext, String phonenu m) {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. Add Contacts

/** * Add contacts * @param mcontext */public static Boolean insertcontact (Context mcontext,string given_name, String mobile_num           ber, String work_email) {contentvalues values = new Contentvalues (); The following action automatically generates a Rawcontactid Uri for a new contact based on Rawcontactid usage already in the rawcontacts table Rawcontacturi = Mcontext.getcontentresolver           (). Insert (Rawcontacts.content_uri, values);           Long Rawcontactid = Contenturis.parseid (Rawcontacturi);               Insert name data to the data table 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);          }//To the data table insert the phone information 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);               }//Insert the data table with the 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 (); Insert your avatar data into the Bitmap Sourcebitmap = Bitmapfactory.decoderesource (Mcontext.getresources (), R.       Drawable.ic_launcher);    Final Bytearrayoutputstream os = new Bytearrayoutputstream ();           Compress Bitmap into PNG encoding with a mass of 100% storage sourcebitmap.compress (Bitmap.CompressFormat.PNG, 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, according to the letter query contact person, according to the phone number fuzzy query

/** * Fuzzy query according to a word in the name * 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) and 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", "Query contact: \ r \ n" + sb.tostring ());}} /** * Fuzzy query based on phone number * */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", "Check Contact name by number:" + name + "----" + "Numbers:" + No. + "\ n"); Here's a hint}}

9. Get contacts, get contactId, get raw_contactid, and get contact data

/** * Read the contact 1, first read the Contacts table, get contactsid; * 2, and then in the Raw_contacts table according to CONTACTSID get Rawcontactsid; * 3, then you can in the data table according to Rawcont Actsid gets the data for the contact. */public static void Querycontactsbycontactidandrawcontactid (Context mcontext) {//Gets the object of the class used to manipulate the data, The basic operation for a contact is to use this object contentresolver CR = Mcontext.getcontentresolver ();//query contacts all records of table cursor Contactcursor = Cr.query (ContactsContract.Contacts.CONTENT_URI, null,null, NULL, NULL); if (Contactcursor.getcount () > 0) {// The cursor initially points to the top of the first record of the query result, and the Execute MoveToNext function determines whether the next record exists, and if so, points to the next record. Otherwise, returns 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 ();//Read number if (Integer.parseint (Contactcursor.getstring (Contactcursor.getcolumnindex ( ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {//Query the contact's number according to query raw_contact_id cursor phonecur = cr.query ( Contactscontract.commondatakinds.phone.content_uri,null,contactscontract.commondatakinds.phone.raw_contact_id+ "=?", new string[] {Rawcontactid}, NULL);//The above contactscontract.commondatakinds.phone.content_uri//can be replaced with the following Phoneuri Phoneuri=uri.parse ("Content://com.android.contacts/data/phones");//A contact may have multiple numbers and need to traverse while ( Phonecur.movetonext ()) {String number = phonecur.getstring (Phonecur.getcolumnindex ( ContactsContract.CommonDataKinds.Phone.NUMBER)); LOG.V ("TAG", "Number:" +number);} Phonecur.close ();}} Contactcursor.close ();}}

10. Delete and update contacts

Delete contact public static void DeleteContact (Context mcontext, long Rawcontactid) {mcontext.getcontentresolver (). Delete ( Contenturis.withappendedid (Rawcontacts.content_uri,rawcontactid), NULL, NULL);} /** * Update Contact * @param mcontext * @param rawcontactid * * Code is not rigorous, * because the contact_id column in the Raw_contacts table is 0, it indicates that the contact was deleted, * should be first through raw _contactid judge whether the contact_id is 0, if not 0, in the update operation * can be directly in the Raw_contacts table, can also be in the Contacts table to judge can */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);}


Host mobile phone contacts, call logs, SMS tool class (constantly improve ... )

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.