下面列出了怎么用android.provider.Contacts的API类实例代码及写法,或者点击链接到github查看源代码。
public static Intent getContactPhoneIntent() {
Intent intent = new Intent(Intent.ACTION_PICK);
/*
* intent.setAction(Intent.ACTION_GET_CONTENT);
* intent.setType(Contacts.Phones.CONTENT_ITEM_TYPE);
*/
if (isCompatible(5)) {
// Don't use constant to allow backward compat simply
intent.setData(Uri.parse("content://com.android.contacts/contacts"));
} else {
// Fallback for android 4
intent.setData(Contacts.People.CONTENT_URI);
}
return intent;
}
public void create(Contact newPhoneContact) throws Exception {
// first, we have to create the contact
ContentValues newPhoneValues = new ContentValues();
newPhoneValues.put(Contacts.People.NAME, newPhoneContact.getName());
Uri newPhoneRow = resolver.insert(Contacts.People.CONTENT_URI, newPhoneValues);
// then we have to add a number
newPhoneValues.clear();
newPhoneValues.put(Contacts.People.Phones.TYPE, Contacts.People.Phones.TYPE_MOBILE);
newPhoneValues.put(Contacts.Phones.NUMBER, newPhoneContact.getNumber());
// insert the new phone number in the database using the returned uri from creating the contact
newPhoneRow = resolver.insert(Uri.withAppendedPath(newPhoneRow, Contacts.People.Phones.CONTENT_DIRECTORY), newPhoneValues);
// if contacts uri returned, there was an error with adding the number
if (newPhoneRow.getPath().contains("people")) {
throw new Exception(String.valueOf(R.string.error_phone_number_not_stored));
}
// if phone uri returned, everything went OK
if (!newPhoneRow.getPath().contains("phones")) {
// some unknown error has happened
throw new Exception(String.valueOf(R.string.error_phone_number_error));
}
}
public Uri retrieveContactUri(Contact contact) {
String id = contact.getId();
String[] projection = new String[] { Contacts.Phones.PERSON_ID };
String path = null;
Cursor result;
if (null != id) {
Uri uri = ContentUris.withAppendedId(Contacts.Phones.CONTENT_URI, Long.valueOf(id));
result = resolver.query(uri, projection, null, null, null);
} else {
String selection = "name='?' AND number='?'";
String[] selectionArgs = new String[] { contact.getName(), contact.getNumber() };
result = resolver.query(Contacts.Phones.CONTENT_URI, projection, selection, selectionArgs, null);
}
if (null != result) {
result.moveToNext();
path = result.getString(0);
result.close();
}
if (null == path) {
return null;
}
return Uri.withAppendedPath(Contacts.People.CONTENT_URI, path);
}
public String[] getContacts(Context context, boolean withNumbers) {
Vector ids = new Vector();
String selection = null;
if (withNumbers) {
selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1";
}
Cursor cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, selection, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
ids.add(contactId);
}
cursor.close();
String[] contacts = new String[ids.size()];
for (int i = 0; i < ids.size(); i++) {
String id = (String) ids.elementAt(i);
contacts[i] = id;
}
return contacts;
}
private void showInfo(Uri contact) {
String[] projection;
if (isSupportsContactsV2()) {
projection = new String[]{ContactsContract.Contacts.DISPLAY_NAME};
} else {
projection = new String[]{Contacts.People.DISPLAY_NAME};
}
Cursor cursor = getContentResolver().query(contact, projection, null, null, null);
cursor.moveToFirst();
String name;
if (isSupportsContactsV2()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
} else {
name = cursor.getString(cursor.getColumnIndex(Contacts.People.DISPLAY_NAME));
}
cursor.close();
infoView.setText(name);
}
public CallerIDResult getContact(String phoneNumber) throws NoResultException {
final Uri uri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, Uri.encode(phoneNumber));
final ContentResolver contentResolver = application.getContentResolver();
final Cursor cursor = contentResolver.query(uri,GET_CONTACT_PROJECTION,null,null,null);
try{
if(cursor.moveToNext()){
CallerIDResult ret = new CallerIDResult();
ret.setPhoneNumber(cursor.getString(NUMBER_COLUMN_INDEX));
ret.setName(cursor.getString(DISPLAY_NAME_COLUMN_INDEX));
return ret;
}else{
throw new NoResultException();
}
}finally{
cursor.close();
}
}
/**
* For versions before Honeycomb, we get all the contact info from the same table.
*/
public void preHoneycombGetContactInfo(Cursor cursor) {
if (cursor.moveToFirst()) {
contactName = guardCursorGetString(cursor, NAME_INDEX);
phoneNumber = guardCursorGetString(cursor, NUMBER_INDEX);
int contactId = cursor.getInt(PERSON_INDEX);
Uri cUri = ContentUris.withAppendedId(Contacts.People.CONTENT_URI, contactId);
contactPictureUri = cUri.toString();
String emailId = guardCursorGetString(cursor, EMAIL_INDEX);
emailAddress = getEmailAddress(emailId);
}
}
protected ContactPicker(ComponentContainer container, Uri intentUri) {
super(container);
activityContext = container.$context();
if (SdkLevel.getLevel() >= SdkLevel.LEVEL_HONEYCOMB_MR1 && intentUri.equals(Contacts.People.CONTENT_URI)) {
this.intentUri = HoneycombMR1Util.getContentUri();
} else if (SdkLevel.getLevel() >= SdkLevel.LEVEL_HONEYCOMB_MR1 && intentUri.equals(Contacts.Phones.CONTENT_URI)) {
this.intentUri = HoneycombMR1Util.getPhoneContentUri();
} else {
this.intentUri = intentUri;
}
}
/**
* Email address getter for pre-Honeycomb.
*/
protected String getEmailAddress(String emailId) {
int id;
try {
id = Integer.parseInt(emailId);
} catch (NumberFormatException e) {
return "";
}
String data = "";
String where = "contact_methods._id = " + id;
String[] projection = {
Contacts.ContactMethods.DATA
};
Cursor cursor = activityContext.getContentResolver().query(
Contacts.ContactMethods.CONTENT_EMAIL_URI,
projection, where, null, null);
try {
if (cursor.moveToFirst()) {
data = guardCursorGetString(cursor, 0);
}
} finally {
cursor.close();
}
// this extra check for null might be redundant, but we given that there are mysterious errors
// on some phones, we'll leave it in just to be extra careful
return ensureNotNull(data);
}
/**
* Retrieves all contacts from the SIM card.
*
* @return ArrayList containing Contact objects from the stored SIM information
*/
public ArrayList<Contact> get() {
final String[] simProjection = new String[] {
Contacts.PeopleColumns.NAME,
Contacts.PhonesColumns.NUMBER,
android.provider.BaseColumns._ID
};
Cursor results = resolver.query(
simUri,
simProjection,
null,
null,
android.provider.Contacts.PeopleColumns.NAME
);
final ArrayList<Contact> simContacts = new ArrayList<>();
if (results != null) {
if (results.getCount() > 0) {
while (results.moveToNext()) {
final Contact simContact = new Contact(
results.getString(results.getColumnIndex(android.provider.BaseColumns._ID)),
results.getString(results.getColumnIndex(Contacts.PeopleColumns.NAME)),
results.getString(results.getColumnIndex(Contacts.PhonesColumns.NUMBER))
);
simContacts.add(simContact);
}
}
results.close();
}
return simContacts;
}
/**
* {@inheritDoc}
*/
public View buildUI(DataType initData) {
if (initData != null) {
editText.setText(initData.getValue());
}
ContentResolver cr = activity.getContentResolver();
List<String> contacts = new ArrayList<String>();
// Form an array specifying which columns to return.
String[] projection = new String[] {People.NAME, People.NUMBER };
// Get the base URI for the People table in the Contacts content provider.
Uri contactsUri = People.CONTENT_URI;
// Make the query.
Cursor cursor = cr.query(contactsUri,
projection, // Which columns to return
null, // Which rows to return (all rows)
null, // Selection arguments (none)
Contacts.People.DEFAULT_SORT_ORDER);
if (cursor.moveToFirst()) {
String name;
String phoneNumber;
int nameColumn = cursor.getColumnIndex(People.NAME);
int phoneColumn = cursor.getColumnIndex(People.NUMBER);
do {
// Get the field values of contacts
name = cursor.getString(nameColumn);
phoneNumber = cursor.getString(phoneColumn);
contacts.add(name + ": " + phoneNumber);
} while (cursor.moveToNext());
}
cursor.close();
String[] contactsStr = new String[]{};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity,
android.R.layout.simple_dropdown_item_1line, contacts.toArray(contactsStr));
editText.setAdapter(adapter);
editText.setThreshold(1);
return(editText);
}
public static InputStream loadContactPhoto(ContentResolver cr, long id, long photo_id) {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
if (input != null) {
return input;
}
byte[] photoBytes = null;
Uri photoUri = ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, photo_id);
Cursor c = cr.query(photoUri, new String[]{ContactsContract.CommonDataKinds.Photo.PHOTO}, null, null, null);
try {
if (c.moveToFirst()) {
photoBytes = c.getBlob(0);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
c.close();
}
if (photoBytes != null) {
return new ByteArrayInputStream(photoBytes);
}
return null;
}
/**
* Pick contact only from contacts with telephone numbers
*/
@SuppressWarnings("deprecation")
public static Intent newPickContactWithPhoneIntent() {
Intent intent;
if (isContacts2ApiSupported()) {
intent = newPickContactIntent(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
} else {
// pre Eclair, use old contacts API
intent = newPickContactIntent(Contacts.Phones.CONTENT_TYPE);
}
return intent;
}
/**
* Pick contact only from contacts with telephone numbers
*/
public static Intent pickContactWithPhone() {
Intent intent;
if (isSupportsContactsV2()) {
intent = pickContact(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
} else { // pre Eclair, use old contacts API
intent = pickContact(Contacts.Phones.CONTENT_TYPE);
}
return intent;
}
public boolean haveContactWithPhoneNumber(String phoneNumber) {
final Uri uri = Uri.withAppendedPath(
Contacts.Phones.CONTENT_FILTER_URL, Uri.encode(phoneNumber));
final Cursor cursor = application.getContentResolver().query(uri,HAVE_CONTACT_PROJECTION,null,null,null);
try{
return cursor.moveToNext();
}finally{
cursor.close();
}
}
public Intent createContactEditor(CallerIDResult result) {
final Intent intent = new Intent(Contacts.Intents.Insert.ACTION, Contacts.People.CONTENT_URI);
intent.putExtra(Contacts.Intents.Insert.NAME, result.getName());
intent.putExtra(Contacts.Intents.Insert.PHONE, result.getPhoneNumber());
if(result.getAddress()!=null) intent.putExtra(Contacts.Intents.Insert.POSTAL, result.getAddress());
return intent;
}
@Override
public Intent getViewContactIntent(Long contactId) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId));
return intent;
}
private static InputStream openMedia(Form form, String mediaPath, MediaSource mediaSource)
throws IOException {
switch (mediaSource) {
case ASSET:
return getAssetsIgnoreCaseInputStream(form,mediaPath);
case REPL_ASSET:
form.assertPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
return new FileInputStream(replAssetPath(mediaPath));
case SDCARD:
form.assertPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
return new FileInputStream(mediaPath);
case FILE_URL:
if (isExternalFileUrl(mediaPath)) {
form.assertPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
}
case URL:
return new URL(mediaPath).openStream();
case CONTENT_URI:
return form.getContentResolver().openInputStream(Uri.parse(mediaPath));
case CONTACT_URI:
// Open the photo for the contact.
InputStream is = null;
if (SdkLevel.getLevel() >= SdkLevel.LEVEL_HONEYCOMB_MR1) {
is = HoneycombMR1Util.openContactPhotoInputStreamHelper(form.getContentResolver(),
Uri.parse(mediaPath));
} else {
is = Contacts.People.openContactPhotoInputStream(form.getContentResolver(),
Uri.parse(mediaPath));
}
if (is != null) {
return is;
}
// There's no photo for the contact.
throw new IOException("Unable to open contact photo " + mediaPath + ".");
}
throw new IOException("Unable to open media " + mediaPath + ".");
}
/**
* Create a new ContactPicker component.
*
* @param container the parent container.
*/
public PhoneNumberPicker(ComponentContainer container) {
super(container, Contacts.Phones.CONTENT_URI);
}
/**
* Create a new ContactPicker component.
*
* @param container the parent container.
*/
public ContactPicker(ComponentContainer container) {
this(container, Contacts.People.CONTENT_URI);
}