ContentProvider(内容提供者)是安卓四大组件之一
它的主要作用:
我们想在自己的应用中访问别的应用或者ContentProvider暴露给我们的一些数据如联系人或短信等。并且想对这些数据进行读取或者修改,这就需要用到ContentProvider。
我们自己的应用,想把自己的一些数据暴露出来,给其他的应用进行读取或操作,也可以用ContentProvider。
例子:
读取手机联系人:
private void getContacts(){ //查询raw_contacts表获得联系人的id ContentResolver resolver = getContentResolver(); Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; //查询联系人数据 cursor = resolver.query(uri, null, null, null, null); while(cursor.moveToNext()) { //获取联系人姓名,手机号码 String cName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); String cNum = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); System.out.println("姓名:" + cName); System.out.println("号码:" + cNum); System.out.println("======================"); } cursor.close(); }
同时要加联系人的权限:
<uses-permission android:name="android.permission.READ_CONTACTS"/>
添加手机联系人:
private void AddContact() throws RemoteException, OperationApplicationException { //使用事务添加联系人 Uri uri = Uri.parse("content://com.android.contacts/raw_contacts"); Uri dataUri = Uri.parse("content://com.android.contacts/data"); ContentResolver resolver = getContentResolver(); ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(); ContentProviderOperation op1 = ContentProviderOperation.newInsert(uri) .withValue("account_name", null) .build(); operations.add(op1); //依次是姓名,号码,邮编 ContentProviderOperation op2 = ContentProviderOperation.newInsert(dataUri) .withValueBackReference("raw_contact_id", 0) .withValue("mimetype", "vnd.android.cursor.item/name") .withValue("data2", "Coder-pig") .build(); operations.add(op2); ContentProviderOperation op3 = ContentProviderOperation.newInsert(dataUri) .withValueBackReference("raw_contact_id", 0) .withValue("mimetype", "vnd.android.cursor.item/phone_v2") .withValue("data1", "13798988888") .withValue("data2", "2") .build(); operations.add(op3); ContentProviderOperation op4 = ContentProviderOperation.newInsert(dataUri) .withValueBackReference("raw_contact_id", 0) .withValue("mimetype", "vnd.android.cursor.item/email_v2") .withValue("data1", "[email protected]") .withValue("data2", "2") .build(); operations.add(op4); //将上述内容添加到手机联系人中~ resolver.applyBatch("com.android.contacts", operations); Toast.makeText(getApplicationContext(), "添加成功", Toast.LENGTH_SHORT).show(); }
<uses-permission android:name="android.permission.WRITE_CONTACTS"/> <uses-permission android:name="android.permission.WRITE_PROFILE"/>
部分参考自菜鸟教程
标签:operations,withValue,联系人,ContentProviderOperation,cursor,ContentProvider,初涉 From: https://www.cnblogs.com/rsy-bxf150/p/17204363.html