下面列出了怎么用android.provider.ContactsContract.Data的API类实例代码及写法,或者点击链接到github查看源代码。
private static void updateNormalizedNumber(Context context, ContentResolver resolver,
String dataId, String number) {
if (TextUtils.isEmpty(number) || TextUtils.isEmpty(dataId)) {
return;
}
final String countryIso = getCurrentCountryIso(context);
if (TextUtils.isEmpty(countryIso)) {
return;
}
final String normalizedNumber = PhoneNumberUtils.formatNumberToE164(number,
getCurrentCountryIso(context));
if (TextUtils.isEmpty(normalizedNumber)) {
return;
}
final ContentValues values = new ContentValues();
values.put(Phone.NORMALIZED_NUMBER, normalizedNumber);
resolver.update(Data.CONTENT_URI, values, Data._ID + "=?", new String[] {dataId});
}
public void deleteMultipleContactsAtOnce(List<String> ids) {
String select = Data.CONTACT_ID + " = ?";
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
for (String id : ids) {
String[] args = new String[] { id };
ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI).withSelection(select, args).build());
}
ContentResolver cr = ContactsManager.getInstance().getContentResolver();
try {
cr.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
Log.e(e);
}
}
@Override
public Intent getAddContactIntent(String displayName, String csipUri) {
Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT, Contacts.CONTENT_URI);
intent.setType(Contacts.CONTENT_ITEM_TYPE);
if (!TextUtils.isEmpty(displayName)) {
intent.putExtra(Insert.NAME, displayName);
}
if (!TextUtils.isEmpty(csipUri)) {
ArrayList<ContentValues> data = new ArrayList<ContentValues>();
ContentValues csipProto = new ContentValues();
csipProto.put(Data.MIMETYPE, CommonDataKinds.Im.CONTENT_ITEM_TYPE);
csipProto.put(CommonDataKinds.Im.PROTOCOL, CommonDataKinds.Im.PROTOCOL_CUSTOM);
csipProto.put(CommonDataKinds.Im.CUSTOM_PROTOCOL, SipManager.PROTOCOL_CSIP);
csipProto.put(CommonDataKinds.Im.DATA, SipUri.getCanonicalSipContact(csipUri, false));
data.add(csipProto);
intent.putParcelableArrayListExtra(Insert.DATA, data);
}
return intent;
}
/**
* Returns the Data id a contact's profile row, or 0 if the user isn't found.
*
* @param resolver a content resolver
* @param uid server-issued unique ID of the contact
* @return the profile Data row id, or 0 if not found
*/
private static long lookupProfile(ContentResolver resolver, String uid) {
final Cursor c = resolver.query(Data.CONTENT_URI, ProfileQuery.PROJECTION, ProfileQuery.SELECTION,
new String[]{uid}, null);
if (c == null) {
return 0;
}
long profileId = 0;
try {
if (c.moveToFirst()) {
profileId = c.getLong(ProfileQuery.COLUMN_ID);
}
} finally {
c.close();
}
return profileId;
}
/**
* Returns the Lookup Key for a contact, or null if user isn't found.
*
* @param resolver a content resolver
* @param uid server-issued unique ID of the contact
* @return the profile Data row id, or 0 if not found
*/
public static String getLookupKey(ContentResolver resolver, String uid) {
final Cursor c = resolver.query(Data.CONTENT_URI, ProfileQuery.PROJECTION, ProfileQuery.SELECTION,
new String[]{uid}, null);
if (c == null) {
return null;
}
String lookupKey = null;
try {
if (c.moveToFirst()) {
lookupKey = c.getString(ProfileQuery.COLUMN_LOOKUP_KEY);
}
} finally {
c.close();
}
return lookupKey;
}
/**
* Synchronously insert a contact with the designated @name into
* the ContactsContentProvider. This code is explained at
* http://developer.android.com/reference/android/provider/ContactsContract.RawContacts.html.
*/
private void addContact(String name,
List<ContentProviderOperation> cpops) {
final int position = cpops.size();
// First part of operation.
cpops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE,
mOps.getAccountType())
.withValue(RawContacts.ACCOUNT_NAME,
mOps.getAccountName())
.withValue(Contacts.STARRED,
1)
.build());
// Second part of operation.
cpops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID,
position)
.withValue(Data.MIMETYPE,
StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME,
name)
.build());
}
/**
* Synchronously insert a contact with the designated @name into
* the ContactsContentProvider. This code is explained at
* http://developer.android.com/reference/android/provider/ContactsContract.RawContacts.html.
*/
private void addContact(String name,
List<ContentProviderOperation> cpops) {
final int position = cpops.size();
// First part of operation.
cpops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE,
mOps.getAccountType())
.withValue(RawContacts.ACCOUNT_NAME,
mOps.getAccountName())
.withValue(Contacts.STARRED,
1)
.build());
// Second part of operation.
cpops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID,
position)
.withValue(Data.MIMETYPE,
StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME,
name)
.build());
}
void updateNativeContactWithPresenceInfo(String value) {
Log.d("[Contact] Adding presence information " + value);
addChangesToCommit(
ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValue(ContactsContract.Data.RAW_CONTACT_ID, mAndroidRawId)
.withValue(
ContactsContract.Data.MIMETYPE,
ContactsManager.getInstance()
.getString(R.string.linphone_address_mime_type))
.withValue("data1", value) // phone number
.withValue(
"data2",
ContactsManager.getInstance()
.getString(R.string.app_name)) // Summary
.withValue("data3", value) // Detail
.build());
}
private void addRecordToBatchInsertOperation(String name,
List<ContentProviderOperation> ops) {
int position = ops.size();
// First part of operation
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, mType)
.withValue(RawContacts.ACCOUNT_NAME, mName)
.withValue(Contacts.STARRED, 1).build());
// Second part of operation
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, position)
.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, name).build());
}
private void addRecordToBatchInsertOperation(String name,
List<ContentProviderOperation> ops) {
int position = ops.size();
// First part of operation
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, mType)
.withValue(RawContacts.ACCOUNT_NAME, mName)
.withValue(Contacts.STARRED, 1).build());
// Second part of operation
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, position)
.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, name).build());
}
public static Photo getPhoto(ContentResolver c, long rawContactId){
Photo photo = new Photo();
String where = ContactsContract.Data.RAW_CONTACT_ID + " = '" + rawContactId
+ "' AND " + ContactsContract.Data.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'";
Cursor c1 = c.query(ContactsContract.Data.CONTENT_URI, new String[] {ContactsContract.CommonDataKinds.Photo.PHOTO, ContactsContract.Data.SYNC2, ContactsContract.Data.SYNC3 }, where , null, null);
if (c1.getCount() > 0){
c1.moveToLast();
photo.data = c1.getBlob(c1.getColumnIndex(ContactsContract.CommonDataKinds.Photo.PHOTO));
photo.timestamp = Long.valueOf(c1.getString(c1.getColumnIndex(ContactsContract.Data.SYNC2)));
photo.url = c1.getString(c1.getColumnIndex(ContactsContract.Data.SYNC3));
}
c1.close();
return photo;
}
public static void addEmail(Context c, long rawContactId, String email){
DeviceUtil.log(c, "adding email", email);
String where = ContactsContract.Data.RAW_CONTACT_ID + " = '" + rawContactId
+ "' AND " + ContactsContract.Data.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE+ "'";
Cursor cursor = c.getContentResolver().query(ContactsContract.Data.CONTENT_URI, new String[] { RawContacts.CONTACT_ID}, where, null, null);
if (cursor.getCount() == 0){
ContentValues contentValues = new ContentValues();
//op.put(ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID, );
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
contentValues.put(ContactsContract.CommonDataKinds.Email.ADDRESS, email);
c.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, contentValues);
}
cursor.close();
}
public static void addBirthday(long rawContactId, String birthday){
String where = ContactsContract.Data.RAW_CONTACT_ID + " = '" + rawContactId
+ "' AND " + ContactsContract.Data.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE
+ "' AND " + ContactsContract.CommonDataKinds.Event.TYPE + " = '" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY + "'";
Cursor cursor = ContactsSyncAdapterService.mContentResolver.query(ContactsContract.Data.CONTENT_URI, null, where, null, null);
int count = cursor.getCount();
cursor.close();
if (count <= 0){
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
contentValues.put(ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY);
contentValues.put(ContactsContract.CommonDataKinds.Event.START_DATE, birthday);
try {
ContactsSyncAdapterService.mContentResolver.insert(ContactsContract.Data.CONTENT_URI, contentValues);
// mContentResolver.applyBatch(ContactsContract.AUTHORITY, operationList);
} catch (Exception e) {
e.printStackTrace();
//Log.e("ERROR:" , e.^);
}
}
}
/**
* Fetch the metadata of a single account. All results will be attached
* to the contact.
* @param contact The contact that should be enriched.
*/
private void fetchMetadata(RawContact contact) {
try {
Cursor cursor = provider.query(
Data.CONTENT_URI,
DATA_PROJECTION_MAP,
Data.RAW_CONTACT_ID + "=?",
new String[]{Long.toString(contact.getID())},
null);
try {
if (cursor.moveToFirst()) {
do {
contact.setMetadata(newMetadata(cursor));
} while (cursor.moveToNext());
}
} finally {
cursor.close();
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
/**
* Store all metadata info into a given contentvalues instance.
* @param values A ContentValues instance.
* @param metadata The Metadata instance to be saved to ContentValues.
*/
private void put(ContentValues values, Metadata metadata) {
if (metadata.getID() > 0) {
values.put(Data._ID, metadata.getID());
}
if (metadata.getRawContactID() > 0) {
values.put(Data.RAW_CONTACT_ID, metadata.getRawContactID());
}
values.put(Data.MIMETYPE, metadata.getMimetype());
for (int i = 0; i < SYNC_FIELDS.length; i++) {
values.put(SYNC_FIELDS[i], metadata.getSync(i));
}
for (int i = 0; i < DATA_FIELDS.length; i++) {
values.put(DATA_FIELDS[i], metadata.getData(i));
}
values.put(Data.DATA15, metadata.getBlob());
}
private Cursor getContactsCursor(ContentResolver cr) {
String req = "(" + Data.MIMETYPE + " = '" + CommonDataKinds.Phone.CONTENT_ITEM_TYPE
+ "' AND " + CommonDataKinds.Phone.NUMBER + " IS NOT NULL "
+ " OR (" + Data.MIMETYPE + " = '" + CommonDataKinds.SipAddress.CONTENT_ITEM_TYPE
+ "' AND " + CommonDataKinds.SipAddress.SIP_ADDRESS + " IS NOT NULL))";
String[] projection = new String[] { Data.CONTACT_ID, Data.DISPLAY_NAME };
String query = Data.DISPLAY_NAME + " IS NOT NULL AND (" + req + ")";
Cursor cursor = cr.query(Data.CONTENT_URI, projection, query, null, " lower(" + Data.DISPLAY_NAME + ") COLLATE UNICODE ASC");
if (cursor == null) {
return cursor;
}
MatrixCursor result = new MatrixCursor(cursor.getColumnNames());
Set<String> groupBy = new HashSet<String>();
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(Data.DISPLAY_NAME));
if (!groupBy.contains(name)) {
groupBy.add(name);
Object[] newRow = new Object[cursor.getColumnCount()];
int contactID = cursor.getColumnIndex(Data.CONTACT_ID);
int displayName = cursor.getColumnIndex(Data.DISPLAY_NAME);
newRow[contactID] = cursor.getString(contactID);
newRow[displayName] = cursor.getString(displayName);
result.addRow(newRow);
}
}
cursor.close();
return result;
}
@Override
public CharSequence transformToSipUri(Context ctxt, Cursor cursor) {
String value = cursor.getString(cursor.getColumnIndex(Data.DATA1));
if (value == null) {
return "";
}
value = value.trim();
return value;
}
@Override
public List<String> getCSipPhonesContact(Context ctxt, Long contactId) {
ArrayList<String> results = new ArrayList<String>();
Uri dataUri = Data.CONTENT_URI;
String dataQuery = Data.MIMETYPE + "='" + CommonDataKinds.Im.CONTENT_ITEM_TYPE + "' "
+ " AND "
+ CommonDataKinds.Im.PROTOCOL + "=" + CommonDataKinds.Im.PROTOCOL_CUSTOM
+ " AND "
+ " LOWER(" + CommonDataKinds.Im.CUSTOM_PROTOCOL + ")='"+SipManager.PROTOCOL_CSIP+"'";
// get csip data
Cursor dataCursor = ctxt.getContentResolver()
.query(dataUri,
new String[] {
CommonDataKinds.Im._ID,
CommonDataKinds.Im.DATA,
},
dataQuery + " AND " + CommonDataKinds.Im.CONTACT_ID + "=?",
new String[] {
Long.toString(contactId)
}, null);
try {
if (dataCursor != null && dataCursor.getCount() > 0) {
dataCursor.moveToFirst();
String val = dataCursor.getString(dataCursor
.getColumnIndex(CommonDataKinds.Im.DATA));
if (!TextUtils.isEmpty(val)) {
results.add(val);
}
}
} catch (Exception e) {
Log.e(THIS_FILE, "Error while looping on data", e);
} finally {
dataCursor.close();
}
return results;
}
/**
* Get the NAME_PROJECTION for PhoneNumberPicker.
*/
public static String[] getNameProjection() {
String[] nameProjection = {
Data.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_THUMBNAIL_URI,
Phone.NUMBER,
};
return nameProjection;
}
/**
* Get the DATA_PROJECTION for ContactPicker and PhoneNumberPicker.
*/
public static String[] getDataProjection() {
String[] dataProjection = {
Data.MIMETYPE,
Email.ADDRESS,
Email.TYPE,
Phone.NUMBER,
Phone.TYPE,
};
return dataProjection;
}
/**
* Get the NEW_PROJECTION for EmailAddressAdapter.
*/
public static String[] getEmailAdapterProjection() {
String[] emailAdapterProjection = {
Data._ID,
Data.DISPLAY_NAME,
Email.ADDRESS,
Data.MIMETYPE,
};
return emailAdapterProjection;
}
/**
* Gets the dataCursor for ContactPicker and PhoneNumberPicker (used for Email and Phone).
*/
public static Cursor getDataCursor(String id, Activity activityContext, String[] dataProjection) {
Cursor dataCursor = activityContext.getContentResolver().query(
Data.CONTENT_URI,
dataProjection,
Data.CONTACT_ID + "=? AND (" + Data.MIMETYPE + "=? OR " + Data.MIMETYPE + "=?)",
new String[] {id, Phone.CONTENT_ITEM_TYPE, Email.CONTENT_ITEM_TYPE},
null);
return dataCursor;
}
public static void insertContact(Context context, String name, String phone) {
// 首先插入空值,再得到rawContactsId ,用于下面插值
ContentValues values = new ContentValues();
// insert a null value
Uri rawContactUri = context.getContentResolver().insert(
RawContacts.CONTENT_URI, values);
long rawContactsId = ContentUris.parseId(rawContactUri);
// 往刚才的空记录中插入姓名
values.clear();
// A reference to the _ID that this data belongs to
values.put(StructuredName.RAW_CONTACT_ID, rawContactsId);
// "CONTENT_ITEM_TYPE" MIME type used when storing this in data table
values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
// The name that should be used to display the contact.
values.put(StructuredName.DISPLAY_NAME, name);
// insert the real values
context.getContentResolver().insert(Data.CONTENT_URI, values);
// 插入电话
values.clear();
values.put(Phone.RAW_CONTACT_ID, rawContactsId);
// String "Data.MIMETYPE":The MIME type of the item represented by this
// row
// String "CONTENT_ITEM_TYPE": MIME type used when storing this in data
// table.
values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
values.put(Phone.NUMBER, phone);
context.getContentResolver().insert(Data.CONTENT_URI, values);
}
/**
* Adds a profile action
*
* @param serverId the uid of the topic object
* @return instance of ContactOperations
*/
ContactOperations addProfileAction(final String serverId) {
mValues.clear();
if (!TextUtils.isEmpty(serverId)) {
mValues.put(Data.MIMETYPE, Utils.MIME_TINODE_PROFILE);
mValues.put(Utils.DATA_PID, serverId);
mValues.put(Utils.DATA_SUMMARY, mContext.getString(R.string.profile_action));
mValues.put(Utils.DATA_DETAIL, mContext.getString(R.string.tinode_message));
addInsertOp();
}
return this;
}
/**
* Adds an insert operation into the batch
*/
private void addInsertOp() {
if (!mIsNewContact) {
mValues.put(Phone.RAW_CONTACT_ID, mRawContactId);
}
ContentProviderOperation.Builder builder = newInsertCpo(Data.CONTENT_URI, mIsSyncContext).withValues(mValues);
if (mIsNewContact) {
builder.withValueBackReference(Data.RAW_CONTACT_ID, mBackReference);
}
mBatchOperation.add(builder.build());
}
/**
* query all sms
* @param context
* @return return a list which would not be null.
*/
public static List<SmsBackupBean> querySms(Context context) {
// create a list to contain contact bean
List<SmsBackupBean> smses = new ArrayList<>();
// select all sms
Cursor cursor = context.getContentResolver()
.query(android.net.Uri.parse(CONTENT_SMS)
, null, null, null, null);
// record all column and value
int colCount = cursor.getColumnCount();
while (cursor.moveToNext()) {
// create sms and add to list
SmsBackupBean sms = new SmsBackupBean();
smses.add(sms);
// create sms datas and set it
List<SmsBackupBean.Data> datas = new ArrayList<>();
sms.setDatas(datas);
// start from 2, for detail to see the database
for (int i = 2; i < colCount; i++) {
String name = cursor.getColumnName(i);
String value = cursor.getString(i);
// System.out.println(name + ":" + value);
// create data and add to datas
datas.add(new SmsBackupBean.Data(name, value));
}
}
cursor.close();
return smses;
}
/**
* This method is called back by Android after the item has
* been inserted into the Contacts Provider to perform the
* completion task(s).
*/
@Override
public void onCompletion(int token,
Uri uri) {
if (token == INSERT_RAW_CONTACT) {
// If the token is INSERT_RAW_CONTACT then
// make a ContentValues object containing
// the data associated with RawContact.
final ContentValues values =
makeRawContactData
(getArgs().getIterator().next(),
uri);
// Initiate an asynchronous insert on the Contacts
// Provider.
getArgs().getAdapter()
.startInsert(this,
INSERT_RAW_CONTACT_DATA,
Data.CONTENT_URI,
values);
} else if (token == INSERT_RAW_CONTACT_DATA) {
// Increment the insertion count.
getArgs().getCounter().increment();
// Calls executeImpl() to trigger insertion of the next
// contact (if any) in the Iterator.
executeImpl();
}
}
/**
* Factory method that creates a ContentValues containing the data
* associated with a RawContact.
*/
private ContentValues makeRawContactData(String displayName,
Uri rawContactUri) {
ContentValues values = new ContentValues();
values.put(Data.RAW_CONTACT_ID,
ContentUris.parseId(rawContactUri));
values.put(Data.MIMETYPE,
StructuredName.CONTENT_ITEM_TYPE);
values.put(StructuredName.DISPLAY_NAME,
displayName);
return values;
}
boolean isLinphoneAddressMimeEntryAlreadyExisting(String value) {
boolean result = false;
ContentResolver resolver =
LinphoneContext.instance().getApplicationContext().getContentResolver();
String[] projection = {"data1", "data3"};
String selection =
ContactsContract.Data.RAW_CONTACT_ID
+ " = ? AND "
+ Data.MIMETYPE
+ " = ? AND data1 = ?";
Cursor c =
resolver.query(
ContactsContract.Data.CONTENT_URI,
projection,
selection,
new String[] {
mAndroidRawId,
ContactsManager.getInstance()
.getString(R.string.linphone_address_mime_type),
value
},
null);
if (c != null) {
if (c.moveToFirst()) {
result = true;
}
c.close();
}
return result;
}
@Override
protected Uri getUri()
{
Uri uri = Data.CONTENT_URI;
if (isFilterQuery())
{
uri = Uri.withAppendedPath(Data.CONTENT_URI, mSearchQuery);
}
return uri;
}