In the development of Android applications, it is often necessary to call the contact interface that comes with the system. After selecting a person, you can obtain the corresponding name and number and return it.
There are also some differences in implementation methods before and after android2.0: The main difference is that the contact API of Version 2.0 and later has changed from the original contacts to contactscontract.
(1)How to retrieve the contact list before 2.0:
Method 1Intent intent = new intent (); intent. setaction (intent. action_pick); intent. setdata (contacts. People. content_uri); startactivityforresult (intent,
Pick_contact
);Method 2IntentIntent = New intent (intent. action_pick );Intent. settype ("contacts. People. content_type"); // vnd. Android. cursor. DIR/personstartactivityforresult (intent,
Pick_contact
);OnactivityresultProtected void onactivityresult (INT requestcode, int resultcode, intent data ){ Super. onactivityresult (requestcode, resultcode, data ); Switch (requestcode ){ Case
Pick_contact
: If (Data = NULL ){ Return; } Uri uri = data. getdata (); Cursor cursor = getcontentresolver (). Query (Uri, null ); Cursor. movetofirst (); String number = cursor. getstring (cursor. getcolumnindexorthrow (phones. Number )); Log. D (TAG, "Number" + number ); Mcontacttext. settext (number ); Mcontacttext. setselection (number. Length ()); Break; Default: Break; } }
(2)How to obtain the contact list after 2.0:Method 1
Intent intent = new intent (intent. action_pick,
Contactscontract. Contacts. content_uri); startactivityforresult (intent, pick_contact );
Method 2
Intent intent = new intent (intent. action_pick );
Intent. settype (contactscontract. Contacts. content_type); // vnd. Android. cursor. DIR/contactStartactivityforresult (intent, pick_contact );
Onactivityresult@ Overridepublic void onactivityresult (INT reqcode, int resultcode, intent data ){ Super. onactivityresult (reqcode, resultcode, data );
Switch (reqcode ){ Case (pick_contact ): If (resultcode = activity. result_ OK ){ Uri contactdata = data. getdata (); Cursor c = Managedquery (contactdata, null ); If (C. movetofirst ()){ String name = C. getstring (C. getcolumnindex (contactscontract. Contacts. display_name )); String hasphone = cursor. getstring (cursor. getcolumnindex (contactscontract. Contacts. has_phone_number )); String phonenumber = NULL; If (hasphone. inclusignorecase ("1 ")){ Hasphone = "true ";} Else { Hasphone = "false ";} If (Boolean. parseboolean (hasphone )){ Cursor Phones =Getcontentresolver (). Query (contactscontract. commondatakinds. Phone. content_uri, null, contactscontract. commondatakinds. Phone. contact_id + "=" + contactid, null, null ); While (phones. movetonext ()){ Phonenumber = phones. getstring (phones. getcolumnindex (contactscontract. commondatakinds. Phone. Number )); } Phones. Close (); } } } Break; }}