android.content.ContentResolver#applyBatch ( )源码实例Demo

下面列出了android.content.ContentResolver#applyBatch ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Linphone4Android   文件: ContactsManager.java
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);
	}
}
 
源代码2 项目: mollyim-android   文件: ContactsDatabase.java
private void applyOperationsInBatches(@NonNull ContentResolver contentResolver,
                                      @NonNull String authority,
                                      @NonNull List<ContentProviderOperation> operations,
                                      int batchSize)
    throws OperationApplicationException, RemoteException
{
  List<List<ContentProviderOperation>> batches = Util.chunk(operations, batchSize);
  for (List<ContentProviderOperation> batch : batches) {
    contentResolver.applyBatch(authority, new ArrayList<>(batch));
  }
}
 
public boolean insertContact(ContentResolver contactAdder, String firstName, String mobileNumber) {
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI).withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null).withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build());
    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, firstName).build());
    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, mobileNumber).withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE).build());
    try {
        contactAdder.applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (Exception e) {
        return false;
    }
    return true;
}
 
源代码4 项目: haxsync   文件: ContactUtil.java
public static void updateContactPhoto(ContentResolver c, long rawContactId, Photo pic, boolean primary){
	ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
	

	
	//insert new picture
	try {
		if(pic.data != null) {
               //delete old picture
               String where = ContactsContract.Data.RAW_CONTACT_ID + " = '" + rawContactId
                       + "' AND " + ContactsContract.Data.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'";
               Log.i(TAG, "Deleting picture: "+where);

               ContentProviderOperation.Builder builder = ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI);
               builder.withSelection(where, null);
               operationList.add(builder.build());
			builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
			builder.withValue(ContactsContract.CommonDataKinds.Photo.RAW_CONTACT_ID, rawContactId);
			builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
			builder.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, pic.data);
			builder.withValue(ContactsContract.Data.SYNC2, String.valueOf(pic.timestamp));
			builder.withValue(ContactsContract.Data.SYNC3, pic.url);
               if (primary)
			    builder.withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
			operationList.add(builder.build());

			
		}
		c.applyBatch(ContactsContract.AUTHORITY,	operationList);

	} catch (Exception e) {
		// TODO Auto-generated catch block
		Log.e("ERROR:" , e.toString());
	}


}
 
源代码5 项目: Trebuchet   文件: LauncherModel.java
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);
                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);
}
 
源代码6 项目: TurboLauncher   文件: LauncherModel.java
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);
}
 
/**
 * Accesses the Contacts content provider directly to insert a new contact.
 * <p>
 * The contact is called "__DUMMY ENTRY" and only contains a name.
 */
private void insertDummyContact() {
    // Two operations are needed to insert a new contact.
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(2);

    // First, set up a new raw contact.
    ContentProviderOperation.Builder op =
            ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null);
    operations.add(op.build());

    // Next, set the name for the contact.
    op = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
            .withValue(ContactsContract.Data.MIMETYPE,
                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                    DUMMY_CONTACT_NAME);
    operations.add(op.build());

    // Apply the operations.
    ContentResolver resolver = getActivity().getContentResolver();
    try {
        resolver.applyBatch(ContactsContract.AUTHORITY, operations);
    } catch (RemoteException | OperationApplicationException e) {
        Snackbar.make(mMessageText.getRootView(), "Could not add a new contact: " +
                e.getMessage(), Snackbar.LENGTH_LONG);
    }
}
 
源代码8 项目: LB-Launcher   文件: LauncherModel.java
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);
}
 
源代码9 项目: arca-android   文件: RequestExecutor.java
@Override
public BatchResult execute(final Batch request) {
    final ContentResolver resolver = getContentResolver();

    try {
        final ContentProviderResult[] results = resolver.applyBatch(request.getAuthority(), request.getOperations());
        return new BatchResult(results);
    } catch (final Exception e) {
        return new BatchResult(new Error(0, e.getMessage()));
    }
}
 
源代码10 项目: XposedSmsCode   文件: SmsCodeWorker.java
private void recordSmsMsg(SmsMsg smsMsg) {
    try {
        Uri smsMsgUri = DBProvider.SMS_MSG_CONTENT_URI;

        ContentValues values = new ContentValues();
        values.put(SmsMsgDao.Properties.Body.columnName, smsMsg.getBody());
        values.put(SmsMsgDao.Properties.Company.columnName, smsMsg.getCompany());
        values.put(SmsMsgDao.Properties.Date.columnName, smsMsg.getDate());
        values.put(SmsMsgDao.Properties.Sender.columnName, smsMsg.getSender());
        values.put(SmsMsgDao.Properties.SmsCode.columnName, smsMsg.getSmsCode());

        ContentResolver resolver = mAppContext.getContentResolver();
        resolver.insert(smsMsgUri, values);
        XLog.d("Add code record succeed by content provider");

        String[] projections = {SmsMsgDao.Properties.Id.columnName};
        String order = SmsMsgDao.Properties.Date.columnName + " ASC";
        Cursor cursor = resolver.query(smsMsgUri, projections, null, null, order);
        if (cursor == null) {
            return;
        }
        int count = cursor.getCount();
        int maxRecordCount = PrefConst.MAX_SMS_RECORDS_COUNT_DEFAULT;
        if (cursor.getCount() > maxRecordCount) {
            // 删除最早的记录,直至剩余数目为 PrefConst.MAX_SMS_RECORDS_COUNT_DEFAULT
            ArrayList<ContentProviderOperation> operations = new ArrayList<>();
            String selection = SmsMsgDao.Properties.Id.columnName + " = ?";
            for (int i = 0; i < count - maxRecordCount; i++) {
                cursor.moveToNext();
                long id = cursor.getLong(cursor.getColumnIndex(SmsMsgDao.Properties.Id.columnName));
                ContentProviderOperation operation = ContentProviderOperation.newDelete(smsMsgUri)
                        .withSelection(selection, new String[]{String.valueOf(id)})
                        .build();

                operations.add(operation);
            }

            resolver.applyBatch(DBProvider.AUTHORITY, operations);
            XLog.d("Remove outdated code records succeed by content provider");
        }

        cursor.close();
    } catch (Exception e1) {
        // ContentProvider dead.
        // Write file to do data transition
        if (CodeRecordRestoreManager.exportToFile(smsMsg)) {
            XLog.d("Export code record to file succeed");
        }
    }
}
 
源代码11 项目: XposedSmsCode   文件: RecordSmsAction.java
private void recordSmsMsg(SmsMsg smsMsg) {
    try {
        Uri smsMsgUri = DBProvider.SMS_MSG_CONTENT_URI;

        ContentValues values = new ContentValues();
        values.put(SmsMsgDao.Properties.Body.columnName, smsMsg.getBody());
        values.put(SmsMsgDao.Properties.Company.columnName, smsMsg.getCompany());
        values.put(SmsMsgDao.Properties.Date.columnName, smsMsg.getDate());
        values.put(SmsMsgDao.Properties.Sender.columnName, smsMsg.getSender());
        values.put(SmsMsgDao.Properties.SmsCode.columnName, smsMsg.getSmsCode());

        ContentResolver resolver = mAppContext.getContentResolver();
        resolver.insert(smsMsgUri, values);
        XLog.d("Add code record succeed by content provider");

        String[] projections = {SmsMsgDao.Properties.Id.columnName};
        String order = SmsMsgDao.Properties.Date.columnName + " ASC";
        Cursor cursor = resolver.query(smsMsgUri, projections, null, null, order);
        if (cursor == null) {
            return;
        }
        int count = cursor.getCount();
        int maxRecordCount = PrefConst.MAX_SMS_RECORDS_COUNT_DEFAULT;
        if (cursor.getCount() > maxRecordCount) {
            // 删除最早的记录,直至剩余数目为 PrefConst.MAX_SMS_RECORDS_COUNT_DEFAULT
            ArrayList<ContentProviderOperation> operations = new ArrayList<>();
            String selection = SmsMsgDao.Properties.Id.columnName + " = ?";
            for (int i = 0; i < count - maxRecordCount; i++) {
                cursor.moveToNext();
                long id = cursor.getLong(cursor.getColumnIndex(SmsMsgDao.Properties.Id.columnName));
                ContentProviderOperation operation = ContentProviderOperation.newDelete(smsMsgUri)
                        .withSelection(selection, new String[]{String.valueOf(id)})
                        .build();

                operations.add(operation);
            }

            resolver.applyBatch(DBProvider.AUTHORITY, operations);
            XLog.d("Remove outdated code records succeed by content provider");
        }

        cursor.close();
    } catch (Exception e1) {
        // ContentProvider dead.
        // Write file to do data transition
        if (CodeRecordRestoreManager.exportToFile(smsMsg)) {
            XLog.d("Export code record to file succeed");
        }
    }
}
 
源代码12 项目: LaunchEnr   文件: LauncherModel.java
/**
 * Update the order of the workspace screens in the database. The array list contains
 * a list of screen ids in the order that they should appear.
 */
public static void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
    final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
    final ContentResolver cr = context.getContentResolver();
    final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;

    // Remove any negative screen ids -- these aren't persisted
    Iterator<Long> iter = screensCopy.iterator();
    while (iter.hasNext()) {
        long id = iter.next();
        if (id < 0) {
            iter.remove();
        }
    }

    Runnable r = new Runnable() {
        @Override
        public void run() {
            ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
            // Clear the table
            ops.add(ContentProviderOperation.newDelete(uri).build());
            int count = screensCopy.size();
            for (int i = 0; i < count; i++) {
                ContentValues v = new ContentValues();
                long screenId = screensCopy.get(i);
                v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
                v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
                ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
            }

            try {
                cr.applyBatch(LauncherProvider.AUTHORITY, ops);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }

            synchronized (sBgDataModel) {
                sBgDataModel.workspaceScreens.clear();
                sBgDataModel.workspaceScreens.addAll(screensCopy);
            }
        }
    };
    runOnWorkerThread(r);
}
 
源代码13 项目: device-database   文件: SyncManager.java
@Override
public Observable<ContentProviderResult> call(ManufacturersAndDevicesResponse response) {
    final ContentResolver contentResolver =
            context.getContentResolver();

    final ArrayList<ContentProviderOperation> operations =
            new ArrayList<>();

    final ContentProviderResult[] results;

    operations.add(ContentProviderOperation
            .newDelete(DevicesContract.Device.CONTENT_URI)
            .build());

    operations.add(ContentProviderOperation
            .newDelete(DevicesContract.Manufacturer.CONTENT_URI)
            .build());

    for (Manufacturer manufacturer : response.getManufacturers()) {
        final ContentProviderOperation manufacturerOperation =
                ContentProviderOperation
                .newInsert(DevicesContract.Manufacturer.CONTENT_URI)
                .withValue(DevicesContract.Manufacturer.SHORT_NAME,
                        manufacturer.getShortName())
                .withValue(DevicesContract.Manufacturer.LONG_NAME,
                        manufacturer.getLongName())
                .build();

        operations.add(manufacturerOperation);

        int manufacturerInsertOperationIndex = operations.size() - 1;

        for (Device device : manufacturer.getDevices()) {
            final ContentProviderOperation deviceOperation =
                    ContentProviderOperation
                    .newInsert(DevicesContract.Device.CONTENT_URI)
                    .withValueBackReference(DevicesContract.Device.MANUFACTURER_ID,
                            manufacturerInsertOperationIndex)
                    .withValue(DevicesContract.Device.MODEL,
                            device.getModel())
                    .withValue(DevicesContract.Device.DISPLAY_SIZE_INCHES,
                            device.getDisplaySizeInches())
                    .withValue(DevicesContract.Device.MEMORY_MB,
                            device.getMemoryMb())
                    .withValue(DevicesContract.Device.NICKNAME,
                            device.getNickname())
                    .build();

            operations.add(deviceOperation);
        }
    }

    try {
        results =
                contentResolver.applyBatch(DevicesContract.AUTHORITY,
                        operations);
    } catch (RemoteException | OperationApplicationException e) {
        throw new RuntimeException(e);
    }

    return Observable.from(results);
}
 
源代码14 项目: Trebuchet   文件: LauncherModel.java
/**
 * Update the order of the workspace screens in the database. The array list contains
 * a list of screen ids in the order that they should appear.
 */
public void updateWorkspaceScreenOrder(final Context context, final ArrayList<Long> screens) {
    final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
    final ContentResolver cr = context.getContentResolver();
    final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;

    // Remove any negative screen ids -- these aren't persisted
    Iterator<Long> iter = screensCopy.iterator();
    while (iter.hasNext()) {
        long id = iter.next();
        if (id < 0) {
            iter.remove();
        }
    }

    Runnable r = new Runnable() {
        @Override
        public void run() {
            ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
            // Clear the table
            ops.add(ContentProviderOperation.newDelete(uri).build());
            int count = screensCopy.size();
            for (int i = 0; i < count; i++) {
                ContentValues v = new ContentValues();
                long screenId = screensCopy.get(i);
                v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
                v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
                ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
            }

            try {
                cr.applyBatch(LauncherProvider.AUTHORITY, ops);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }

            synchronized (sBgLock) {
                sBgWorkspaceScreens.clear();
                sBgWorkspaceScreens.addAll(screensCopy);
                savePageCount(context);
            }
        }
    };
    runOnWorkerThread(r);
}
 
源代码15 项目: RememBirthday   文件: CalendarLoader.java
/**
 * Gets calendar id, when no calendar is present, create one!
 */
public static long getCalendar(Context context) {
    ContentResolver contentResolver = context.getContentResolver();

    // Find the calendar if we've got one
    Uri calenderUri = getBirthdayAdapterUri(context, CalendarContract.Calendars.CONTENT_URI);

    // be sure to select the birthday calendar only (additionally to appendQueries in
    // getBirthdayAdapterUri for Android < 4)
    Cursor cursor = contentResolver.query(calenderUri, new String[]{BaseColumns._ID},
            CalendarContract.Calendars.ACCOUNT_NAME + " = ? AND " + CalendarContract.Calendars.ACCOUNT_TYPE + " = ?",
            new String[]{CalendarAccount.getAccountName(context), CalendarAccount.getAccountType(context)}, null);

    try {
        if (cursor != null && cursor.moveToNext()) {
            return cursor.getLong(0);
        } else {
            ArrayList<ContentProviderOperation> operationList = new ArrayList<>();

            ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newInsert(calenderUri);
            builder.withValue(CalendarContract.Calendars.ACCOUNT_NAME, CalendarAccount.getAccountName(context));
            builder.withValue(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarAccount.getAccountType(context));
            builder.withValue(CalendarContract.Calendars.NAME, CALENDAR_COLUMN_NAME);
            builder.withValue(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
                    context.getString(R.string.calendar_display_name));
            builder.withValue(CalendarContract.Calendars.CALENDAR_COLOR, PreferencesManager.getCustomCalendarColor(context));
            //if (BuildConfig.DEBUG) {
            //    builder.withValue(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_EDITOR);
            //} else {
            builder.withValue(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_READ);
            //}
            builder.withValue(CalendarContract.Calendars.OWNER_ACCOUNT, CalendarAccount.getAccountName(context));
            builder.withValue(CalendarContract.Calendars.SYNC_EVENTS, 1);
            builder.withValue(CalendarContract.Calendars.VISIBLE, 1);
            operationList.add(builder.build());
            try {
                contentResolver.applyBatch(CalendarContract.AUTHORITY, operationList);
            } catch (Exception e) {
                Log.e(TAG, "getCalendar() failed", e);
                return -1;
            }
            return getCalendar(context);
        }
    } finally {
        if (cursor != null && !cursor.isClosed())
            cursor.close();
    }
}
 
源代码16 项目: Telegram-FOSS   文件: ContactsController.java
public void createOrUpdateConnectionServiceContact(int id, String firstName, String lastName) {
    if (!hasContactsPermission())
        return;
    try {
        ContentResolver resolver = ApplicationLoader.applicationContext.getContentResolver();
        ArrayList<ContentProviderOperation> ops = new ArrayList<>();

        final Uri groupsURI = ContactsContract.Groups.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build();
        final Uri rawContactsURI = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build();

        // 1. Check if we already have the invisible group/label and create it if we don't
        Cursor cursor = resolver.query(groupsURI, new String[]{ContactsContract.Groups._ID},
                ContactsContract.Groups.TITLE + "=? AND " + ContactsContract.Groups.ACCOUNT_TYPE + "=? AND " + ContactsContract.Groups.ACCOUNT_NAME + "=?",
                new String[]{"TelegramConnectionService", systemAccount.type, systemAccount.name}, null);
        int groupID;
        if (cursor != null && cursor.moveToFirst()) {
            groupID = cursor.getInt(0);
            /*ops.add(ContentProviderOperation.newUpdate(groupsURI)
                    .withSelection(ContactsContract.Groups._ID+"=?", new String[]{groupID+""})
                    .withValue(ContactsContract.Groups.DELETED, 0)
                    .build());*/
        } else {
            ContentValues values = new ContentValues();
            values.put(ContactsContract.Groups.ACCOUNT_TYPE, systemAccount.type);
            values.put(ContactsContract.Groups.ACCOUNT_NAME, systemAccount.name);
            values.put(ContactsContract.Groups.GROUP_VISIBLE, 0);
            values.put(ContactsContract.Groups.GROUP_IS_READ_ONLY, 1);
            values.put(ContactsContract.Groups.TITLE, "TelegramConnectionService");
            Uri res = resolver.insert(groupsURI, values);
            groupID = Integer.parseInt(res.getLastPathSegment());
        }
        if (cursor != null)
            cursor.close();

        // 2. Find the existing ConnectionService contact and update it or create it
        cursor = resolver.query(ContactsContract.Data.CONTENT_URI, new String[]{ContactsContract.Data.RAW_CONTACT_ID},
                ContactsContract.Data.MIMETYPE + "=? AND " + ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "=?",
                new String[]{ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE, groupID + ""}, null);
        int backRef = ops.size();
        if (cursor != null && cursor.moveToFirst()) {
            int contactID = cursor.getInt(0);
            ops.add(ContentProviderOperation.newUpdate(rawContactsURI)
                    .withSelection(ContactsContract.RawContacts._ID + "=?", new String[]{contactID + ""})
                    .withValue(ContactsContract.RawContacts.DELETED, 0)
                    .build());
            ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                    .withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
                            new String[]{contactID + "", ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE})
                    .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, "+99084" + id)
                    .build());
            ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                    .withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
                            new String[]{contactID + "", ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE})
                    .withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, firstName)
                    .withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, lastName)
                    .build());
        } else {
            ops.add(ContentProviderOperation.newInsert(rawContactsURI)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, systemAccount.type)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, systemAccount.name)
                    .withValue(ContactsContract.RawContacts.RAW_CONTACT_IS_READ_ONLY, 1)
                    .withValue(ContactsContract.RawContacts.AGGREGATION_MODE, ContactsContract.RawContacts.AGGREGATION_MODE_DISABLED)
                    .build());
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, backRef)
                    .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, firstName)
                    .withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, lastName)
                    .build());
            // The prefix +990 isn't assigned to anything, so our "phone number" is going to be +990-TG-UserID
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, backRef)
                    .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, "+99084" + id)
                    .build());
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, backRef)
                    .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID, groupID)
                    .build());
        }
        if (cursor != null)
            cursor.close();

        resolver.applyBatch(ContactsContract.AUTHORITY, ops);

    } catch (Exception x) {
        FileLog.e(x);
    }
}
 
private static long getCalendar(Context context) {

        ContentResolver contentResolver = context.getContentResolver();

        // Find the calendar if we've got one
        Uri calenderUri = CalendarContract.Calendars.CONTENT_URI.buildUpon().appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
                .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, ACCOUNT_NAME)
                .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, ACCOUNT_TYPE).build();


        Cursor cursor = contentResolver.query(calenderUri, new String[]{BaseColumns._ID},
                CalendarContract.Calendars.ACCOUNT_NAME + " = ? AND " + CalendarContract.Calendars.ACCOUNT_TYPE + " = ?",
                new String[]{ACCOUNT_NAME, ACCOUNT_TYPE}, null);

        try {
            if (cursor != null && cursor.moveToNext()) {
                return cursor.getLong(0);
            } else {
                ArrayList<ContentProviderOperation> operationList = new ArrayList<>();

                ContentProviderOperation.Builder builder = ContentProviderOperation
                        .newInsert(calenderUri);
                builder.withValue(CalendarContract.Calendars.ACCOUNT_NAME, ACCOUNT_NAME);
                builder.withValue(CalendarContract.Calendars.ACCOUNT_TYPE, ACCOUNT_TYPE);
                builder.withValue(CalendarContract.Calendars.NAME, CALENDAR_COLUMN_NAME);
                builder.withValue(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
                        context.getString(R.string.appName));
                builder.withValue(CalendarContract.Calendars.CALENDAR_COLOR, context.getResources().getColor(R.color.colorPrimary));
                builder.withValue(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_READ);
                builder.withValue(CalendarContract.Calendars.SYNC_EVENTS, 0);
                builder.withValue(CalendarContract.Calendars.VISIBLE, 1);

                operationList.add(builder.build());
                try {
                    contentResolver.applyBatch(CalendarContract.AUTHORITY, operationList);
                } catch (Exception e) {
                    e.printStackTrace();
                    return -1;
                }
                return getCalendar(context);
            }
        } finally {
            if (cursor != null && !cursor.isClosed())
                cursor.close();
        }
    }
 
源代码18 项目: LB-Launcher   文件: LauncherModel.java
/**
 * Update the order of the workspace screens in the database. The array list contains
 * a list of screen ids in the order that they should appear.
 */
void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
    // Log to disk
    Launcher.addDumpLog(TAG, "11683562 - updateWorkspaceScreenOrder()", true);
    Launcher.addDumpLog(TAG, "11683562 -   screens: " + TextUtils.join(", ", screens), true);

    final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
    final ContentResolver cr = context.getContentResolver();
    final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;

    // Remove any negative screen ids -- these aren't persisted
    Iterator<Long> iter = screensCopy.iterator();
    while (iter.hasNext()) {
        long id = iter.next();
        if (id < 0) {
            iter.remove();
        }
    }

    Runnable r = new Runnable() {
        @Override
        public void run() {
            ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
            // Clear the table
            ops.add(ContentProviderOperation.newDelete(uri).build());
            int count = screensCopy.size();
            for (int i = 0; i < count; i++) {
                ContentValues v = new ContentValues();
                long screenId = screensCopy.get(i);
                v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
                v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
                ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
            }

            try {
                cr.applyBatch(LauncherProvider.AUTHORITY, ops);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }

            synchronized (sBgLock) {
                sBgWorkspaceScreens.clear();
                sBgWorkspaceScreens.addAll(screensCopy);
            }
        }
    };
    runOnWorkerThread(r);
}
 
源代码19 项目: linphone-android   文件: AndroidContact.java
void saveChangesCommited() {
    if (ContactsManager.getInstance().hasReadContactsAccess() && mChangesToCommit.size() > 0) {
        try {
            ContentResolver contentResolver =
                    LinphoneContext.instance().getApplicationContext().getContentResolver();
            ContentProviderResult[] results =
                    contentResolver.applyBatch(ContactsContract.AUTHORITY, mChangesToCommit);
            if (results != null
                    && results.length > 0
                    && results[0] != null
                    && results[0].uri != null) {
                String rawId = String.valueOf(ContentUris.parseId(results[0].uri));
                if (mAndroidId == null) {
                    Log.i("[Contact] Contact created with RAW ID " + rawId);
                    mAndroidRawId = rawId;
                    if (mTempPicture != null) {
                        Log.i(
                                "[Contact] Contact has been created, raw is is available, time to set the photo");
                        setPhoto(mTempPicture);
                    }

                    final String[] projection =
                            new String[] {ContactsContract.RawContacts.CONTACT_ID};
                    final Cursor cursor =
                            contentResolver.query(results[0].uri, projection, null, null, null);
                    if (cursor != null) {
                        cursor.moveToNext();
                        long contactId = cursor.getLong(0);
                        mAndroidId = String.valueOf(contactId);
                        cursor.close();
                        Log.i("[Contact] Contact created with ID " + mAndroidId);
                    }
                } else {
                    if (mAndroidRawId == null || !isAndroidRawIdLinphone) {
                        Log.i(
                                "[Contact] Linphone RAW ID "
                                        + rawId
                                        + " created from existing RAW ID "
                                        + mAndroidRawId);
                        mAndroidRawId = rawId;
                        isAndroidRawIdLinphone = true;
                    }
                }
            }
        } catch (Exception e) {
            Log.e("[Contact] Exception while saving changes: " + e);
        } finally {
            mChangesToCommit.clear();
        }
    }
}
 
public void saveContact(ReadableMap contact, Promise promise) {
    try {

        ArrayList<ContentProviderOperation> ops = (new Contact(contact)).createOps();


        ContentResolver cr = this.context.getContentResolver();
        ContentProviderResult[] result = cr.applyBatch(ContactsContract.AUTHORITY, ops);

        promise.resolve(null);

    } catch (Exception e) {
        promise.reject(e);
    }
}