下面列出了怎么用android.content.ContentProviderOperation的API类实例代码及写法,或者点击链接到github查看源代码。
private void addContactVoiceSupport(List<ContentProviderOperation> operations,
@NonNull String address, long rawContactId)
{
operations.add(ContentProviderOperation.newUpdate(RawContacts.CONTENT_URI)
.withSelection(RawContacts._ID + " = ?", new String[] {String.valueOf(rawContactId)})
.withValue(RawContacts.SYNC4, "true")
.build());
operations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build())
.withValue(ContactsContract.Data.RAW_CONTACT_ID, rawContactId)
.withValue(ContactsContract.Data.MIMETYPE, CALL_MIMETYPE)
.withValue(ContactsContract.Data.DATA1, address)
.withValue(ContactsContract.Data.DATA2, context.getString(R.string.app_name))
.withValue(ContactsContract.Data.DATA3, context.getString(R.string.ContactsDatabase_signal_call_s, address))
.withYieldAllowed(true)
.build());
}
@Override
public ContentProviderResult[] applyBatch(@NonNull ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {
if (operations.size() > 0) {
ContentProvider provider = getContentProvider(operations.get(0).getUri());
if (provider != null) {
try {
for (ContentProviderOperation operation : operations) {
Uri pluginUri = Uri.parse(operation.getUri().getQueryParameter(IntentConstant.EXTRA_TARGET_URI_KEY));
ReflectionUtils.on(operation).set("mUri", pluginUri);
}
return provider.applyBatch(operations);
} catch (Exception e) {
return new ContentProviderResult[0];
}
}
}
return new ContentProviderResult[0];
}
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);
}
}
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());
}
/**
* Apply the given set of {@link ContentProviderOperation}, executing inside
* a {@link SQLiteDatabase} transaction. All changes will be rolled back if
* any single one fails.
*/
@NonNull
public ContentProviderResult[] applyBatch(@NonNull ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.beginTransaction();
try {
final int numOperations = operations.size();
final ContentProviderResult[] results = new ContentProviderResult[numOperations];
for (int i = 0; i < numOperations; i++) {
results[i] = operations.get(i).apply(this, results, i);
}
db.setTransactionSuccessful();
return results;
} finally {
db.endTransaction();
}
}
@Override
protected Exception doInBackground(Void... voids) {
try {
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ContentProviderOperation.Builder contentBuilder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data._ID + " =? AND " +
ContactsContract.Data.MIMETYPE + " =? AND " +
ContactsContract.CommonDataKinds.Event.START_DATE + " =? AND " +
ContactsContract.CommonDataKinds.Event.TYPE + " =?"
, new String[]{String.valueOf(dataId),
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE,
oldBirthday.toBackupString(),
String.valueOf(ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY)})
.withValue(ContactsContract.CommonDataKinds.Event.START_DATE, birthday.toBackupString());
Log.d(getClass().getSimpleName(), "Update birthday " + oldBirthday + " to " + birthday);
ops.add(contentBuilder.build());
ContentProviderResult[] results = context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
if(results[0].count == 0)
return new Exception("Unable to update birthday");
} catch(Exception e) {
return e;
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {
ContentProviderResult[] result = null;
SQLiteDatabase db = this.getDatabaseHelper().getWritableDatabase();
db.beginTransaction();
try {
result = super.applyBatch(operations);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
return result;
}
/**
* Apply the given set of {@link ContentProviderOperation}, executing inside
* a {@link SQLiteDatabase} transaction. All changes will be rolled back if
* any single one fails.
*/
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.beginTransaction();
try {
final int numOperations = operations.size();
final ContentProviderResult[] results = new ContentProviderResult[numOperations];
for (int i = 0; i < numOperations; i++) {
results[i] = operations.get(i).apply(this, results, i);
}
db.setTransactionSuccessful();
return results;
} finally {
db.endTransaction();
}
}
@NonNull
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {
try {
Field uriField = ContentProviderOperation.class.getDeclaredField("mUri");
uriField.setAccessible(true);
for (ContentProviderOperation operation : operations) {
Uri pluginUri = Uri.parse(operation.getUri().getQueryParameter(KEY_URI));
uriField.set(operation, pluginUri);
}
} catch (Exception e) {
return new ContentProviderResult[0];
}
if (operations.size() > 0) {
ContentProvider provider = getContentProvider(operations.get(0).getUri());
if (provider != null) {
return provider.applyBatch(operations);
}
}
return new ContentProviderResult[0];
}
/**
* Apply the given set of {@link ContentProviderOperation}, executing inside
* a {@link SQLiteDatabase} transaction. All changes will be rolled back if
* any single one fails.
*/
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
db.beginTransaction();
try {
final int numOperations = operations.size();
final ContentProviderResult[] results = new ContentProviderResult[numOperations];
for (int i = 0; i < numOperations; i++) {
results[i] = operations.get(i).apply(this, results, i);
}
db.setTransactionSuccessful();
return results;
} finally {
db.endTransaction();
}
}
private ArrayList<ContentProviderOperation> prepareRemoveSharesInFile(
String filePath, ArrayList<ContentProviderOperation> preparedOperations) {
String where = ProviderTableMeta.OCSHARES_PATH + "=?" + " AND "
+ ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?";
String[] whereArgs = new String[]{filePath, mAccount.name};
preparedOperations.add(
ContentProviderOperation.newDelete(ProviderTableMeta.CONTENT_URI_SHARE).
withSelection(where, whereArgs).
build()
);
return preparedOperations;
}
public static ContentProviderOperation deleteAll(Context context, long eventId) {
ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(CalendarLoader.getBirthdayAdapterUri(context, CalendarContract.Reminders.CONTENT_URI))
.withSelection(CalendarContract.Reminders.EVENT_ID + " =?"
, new String[]{String.valueOf(eventId)});
return builder.build();
}
@NonNull
@Override
public ContentProviderOperation.Builder updatedBuilder(@NonNull TransactionContext transactionContext, @NonNull ContentProviderOperation.Builder builder)
{
String value = TextUtils.join(",",
new Mapped<>(DateTime::toString, new Mapped<>(dt -> dt.isFloating() ? dt : dt.shiftTimeZone(DateTime.UTC), mDateTimes)));
return builder.withValue(mField, value.isEmpty() ? null : value);
}
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.beginTransaction();
try {
ContentProviderResult[] result = super.applyBatch(operations);
db.setTransactionSuccessful();
reloadLauncherIfExternal();
return result;
} finally {
db.endTransaction();
}
}
private void removeTextSecureRawContact(List<ContentProviderOperation> operations,
Account account, long rowId)
{
operations.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI.buildUpon()
.appendQueryParameter(RawContacts.ACCOUNT_NAME, account.name)
.appendQueryParameter(RawContacts.ACCOUNT_TYPE, account.type)
.appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build())
.withYieldAllowed(true)
.withSelection(BaseColumns._ID + " = ?", new String[] {String.valueOf(rowId)})
.build());
}
private void buildNode(boolean isInsert, Node node,
ArrayList<ContentProviderOperation> list) {
Uri allVideosUri = V2exContract.addCallerIsSyncAdapterParameter(
V2exContract.Nodes.CONTENT_URI);
Uri thisVideoUri = V2exContract.addCallerIsSyncAdapterParameter(
V2exContract.Nodes.buildNodeUri(String.valueOf(node.id)));
ContentProviderOperation.Builder builder;
if (isInsert) {
builder = ContentProviderOperation.newInsert(allVideosUri);
} else {
builder = ContentProviderOperation.newUpdate(thisVideoUri);
}
if (TextUtils.isEmpty(String.valueOf(node.id))) {
LOGW(TAG, "Ignoring feed with missing feed ID.");
return;
}
list.add(builder.withValue(V2exContract.Nodes.NODE_ID, node.id)
.withValue(V2exContract.Nodes.NODE_NAME, node.name)
.withValue(V2exContract.Nodes.NODE_URL, node.url)
.withValue(V2exContract.Nodes.NODE_TITLE, node.title)
.withValue(V2exContract.Nodes.NODE_TITLE_ALTERNATIVE, node.title_alternative)
.withValue(V2exContract.Nodes.NODE_TOPICS, node.topics)
.withValue(V2exContract.Nodes.NODE_HEADER, node.header)
.withValue(V2exContract.Nodes.NODE_FOOTER, node.footer)
.withValue(V2exContract.Nodes.NODE_CREATED, node.created)
.withValue(V2exContract.Nodes.NODE_AVATAR_MINI, node.avatar_mini)
.withValue(V2exContract.Nodes.NODE_AVATAR_NORMAL, node.avatar_normal)
.withValue(V2exContract.Nodes.NODE_AVATAR_LARGE, node.avatar_large)
.withValue(V2exContract.Nodes.NODE_IMPORT_HASHCODE, node.getImportHashcode())
.build());
}
static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
final ArrayList<ItemInfo> items, final String callingFunction) {
final ContentResolver cr = context.getContentResolver();
final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Runnable r = new Runnable() {
public void run() {
ArrayList<ContentProviderOperation> ops =
new ArrayList<ContentProviderOperation>();
int count = items.size();
for (int i = 0; i < count; i++) {
ItemInfo item = items.get(i);
final long itemId = item.id;
final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
ContentValues values = valuesList.get(i);
ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
updateItemArrays(item, itemId, stackTrace);
}
try {
cr.applyBatch(LauncherProvider.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
}
}
};
runOnWorkerThread(r);
}
/**
* Creates and returns a ContentProviderOperation that assigns the data array as the
* sync state for the given account.
* @param uri the uri of the specific sync state to set
* @param data the byte[] that contains the sync state
* @return the new ContentProviderOperation that assigns the data array as the
* account's sync state
*/
public static ContentProviderOperation newUpdateOperation(Uri uri, byte[] data) {
ContentValues values = new ContentValues();
values.put(Columns.DATA, data);
return ContentProviderOperation
.newUpdate(uri)
.withValues(values)
.build();
}
private boolean deleteContact(Contact contact){
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
.withSelection(ContactsContract.RawContacts.CONTACT_ID + "=?", new String[]{String.valueOf(contact.identifier)})
.build());
try {
contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
return true;
} catch (Exception e) {
return false;
}
}
/**
* Update the specific event, id must be specified
* @param event Event to update
* @return ContentProviderOperation to apply or null if no id
*/
public static ContentProviderOperation update(CalendarEvent event) {
if(event.hasId()) {
ContentProviderOperation.Builder builder;
builder = ContentProviderOperation.newUpdate(
ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, event.getId()));
// Push values
assignValuesInBuilder(builder, event);
Log.d(TAG, "Build update event : " + event);
return builder.build();
} else {
Log.e(TAG, "Can't update the event, there is no id");
return null;
}
}
/**
* Add an address to a list of database actions to be performed
*
* @param ops the list of database actions
* @param address the item to be inserted
*/
private void insertAddress(ArrayList<ContentProviderOperation> ops,
JSONObject address) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, getAddressType(getJsonString(address, "type")))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, getJsonString(address, "formatted"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, getJsonString(address, "streetAddress"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, getJsonString(address, "locality"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION, getJsonString(address, "region"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, getJsonString(address, "postalCode"))
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, getJsonString(address, "country"))
.build());
}
private boolean deleteContact(Contact contact){
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
.withSelection(ContactsContract.RawContacts.CONTACT_ID + "=?", new String[]{String.valueOf(contact.identifier)})
.build());
try {
contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
return true;
} catch (Exception e) {
return false;
}
}
public static ContentProviderOperation delete(Context context, long eventId, Reminder reminder) {
ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(CalendarLoader.getBirthdayAdapterUri(context, CalendarContract.Reminders.CONTENT_URI))
.withSelection(CalendarContract.Reminders._ID + " =?"
+ " AND " + CalendarContract.Reminders.EVENT_ID + " =?"
, new String[]{String.valueOf(reminder.getId()),
String.valueOf(eventId)});
return builder.build();
}
/**
* Add an organization to a list of database actions to be performed
*
* @param ops the list of database actions
* @param org the item to be inserted
*/
private void insertOrganization(ArrayList<ContentProviderOperation> ops,
JSONObject org) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Organization.TYPE, getOrgType(getJsonString(org, "type")))
.withValue(ContactsContract.CommonDataKinds.Organization.DEPARTMENT, getJsonString(org, "department"))
.withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, getJsonString(org, "name"))
.withValue(ContactsContract.CommonDataKinds.Organization.TITLE, getJsonString(org, "title"))
.build());
}
/**
* Add a website to a list of database actions to be performed
*
* @param ops the list of database actions
* @param website the item to be inserted
*/
private void insertWebsite(ArrayList<ContentProviderOperation> ops,
JSONObject website) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Website.DATA, getJsonString(website, "value"))
.withValue(ContactsContract.CommonDataKinds.Website.TYPE, getContactType(getJsonString(website, "type")))
.build());
}
private void processPhotos() {
Cursor cursor = getIdenticonPhotos();
final int totalPhotos = cursor.getCount();
int currentPhoto = 1;
while (cursor.moveToNext()) {
final long contactId = cursor.getLong(0);
updateNotification(getString(R.string.identicons_remove_service_running_title),
String.format(getString(R.string.identicons_remove_service_contact_summary),
currentPhoto++, totalPhotos)
);
byte[] data = cursor.getBlob(1);
if (IdenticonUtils.isIdenticon(data))
removeIdenticon(contactId);
}
cursor.close();
if (!mOps.isEmpty()) {
updateNotification(getString(R.string.identicons_remove_service_running_title),
getString(R.string.identicons_remove_service_contact_summary_finishing));
try {
// Perform operations in batches of 100, to avoid TransactionTooLargeExceptions
for (int i = 0, j = mOps.size(); i < j; i += 100)
getContentResolver().applyBatch(ContactsContract.AUTHORITY,
new ArrayList<ContentProviderOperation>(mOps.subList(i, i + Math.min(100, j - i))));
} catch (RemoteException | OperationApplicationException e) {
Log.e(TAG, "Unable to apply batch", e);
}
}
}
@Override
public void makeContentProviderOperations(ArrayList<ContentProviderOperation> list) {
Uri uri = V2exContract.Nodes.CONTENT_URI;
HashMap<String, String> nodeHashcodes = loadNodeHashcodes();
HashSet<String> nodesToKeep = new HashSet<>();
boolean isIncrementalUpdate = nodeHashcodes != null && nodeHashcodes.size() > 0;
if (isIncrementalUpdate) {
LOGD(TAG, "Doing incremental update for nodes.");
} else {
LOGD(TAG, "Doing FULL (non incremental) update for nodes.");
list.add(ContentProviderOperation.newDelete(uri).build());
}
int updatedNodes = 0;
for (Node node : mNodes.values()) {
String hashCode = node.getImportHashcode();
nodesToKeep.add(String.valueOf(node.id));
// add node, if necessary
if (!isIncrementalUpdate || !nodeHashcodes.containsKey(String.valueOf(node.id)) ||
!nodeHashcodes.get(String.valueOf(node.id)).equals(hashCode)) {
++updatedNodes;
boolean isNew = !isIncrementalUpdate || !nodeHashcodes.containsKey(String.valueOf(node.id));
buildNode(isNew, node, list);
}
}
LOGD(TAG, "Nodes: " + (isIncrementalUpdate ? "INCREMENTAL" : "FULL") + " update. " +
updatedNodes + " to update, New total: " + mNodes.size());
}
private static LinphoneContact createAndroidContact() {
LinphoneContact contact = new LinphoneContact();
contact.changesToCommit.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
.withValue(ContactsContract.RawContacts.AGGREGATION_MODE, ContactsContract.RawContacts.AGGREGATION_MODE_DEFAULT)
.build());
contact.setAndroidId("0");
return contact;
}
private boolean importWorkspace() throws Exception {
ArrayList<Long> allScreens = LauncherDbUtils.getScreenIdsFromCursor(
mContext.getContentResolver().query(mOtherScreensUri, null, null, null,
LauncherSettings.WorkspaceScreens.SCREEN_RANK));
// During import we reset the screen IDs to 0-indexed values.
if (allScreens.isEmpty()) {
// No thing to migrate
return false;
}
mHotseatSize = mMaxGridSizeX = mMaxGridSizeY = 0;
// Build screen update
ArrayList<ContentProviderOperation> screenOps = new ArrayList<>();
int count = allScreens.size();
LongSparseArray<Long> screenIdMap = new LongSparseArray<>(count);
for (int i = 0; i < count; i++) {
ContentValues v = new ContentValues();
v.put(LauncherSettings.WorkspaceScreens._ID, i);
v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
screenIdMap.put(allScreens.get(i), (long) i);
screenOps.add(ContentProviderOperation.newInsert(
LauncherSettings.WorkspaceScreens.CONTENT_URI).withValues(v).build());
}
mContext.getContentResolver().applyBatch(ProviderConfig.AUTHORITY, screenOps);
importWorkspaceItems(allScreens.get(0), screenIdMap);
GridSizeMigrationTask.markForMigration(mContext, mMaxGridSizeX, mMaxGridSizeY, mHotseatSize);
// Create empty DB flag.
LauncherSettings.Settings.call(mContext.getContentResolver(),
LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG);
return true;
}
HotseatParserCallback(
HashSet<String> existingApps, LongArrayMap<Object> existingItems,
ArrayList<ContentProviderOperation> outOps, int startItemId, int requiredSize) {
mExisitingApps = existingApps;
mExistingItems = existingItems;
mOutOps = outOps;
mRequiredSize = requiredSize;
mStartItemId = startItemId;
}