Android利用ContentProviderOperation添加联系人

Android添加联系人有两种方式:

1. 直接调用插入语句,先插入一个空Item,得到一个id,然后给这个id对应的插入其他信息,如姓名,号码,邮件等;

2. 利用ContentProviderOperation, 在系统应用Phonebook中就是采用这种方式, 代码如下:

实现了插入姓名,号码以及头像。

  1     private boolean saveUpdatedPhoto(long rawContactId, File photoFile) {
  2         final Uri outputUri = Uri.withAppendedPath(ContentUris.withAppendedId(
  3                 RawContacts.CONTENT_URI, rawContactId),
  4                 RawContacts.DisplayPhoto.CONTENT_DIRECTORY);
  5         boolean result = false;
  6         try {
  7             final FileOutputStream outputStream = getContentResolver()
  8                     .openAssetFileDescriptor(outputUri, "rw")
  9                     .createOutputStream();
 10             try {
 11                 final FileInputStream inputStream = new FileInputStream(
 12                         photoFile);
 13                 try {
 14                     final byte[] buffer = new byte[16 * 1024];
 15                     int length;
 16                     int totalLength = 0;
 17                     while ((length = inputStream.read(buffer)) > 0) {
 18                         outputStream.write(buffer, 0, length);
 19                         totalLength += length;
 20                     }
 21                     result = true;
 22                 } finally {
 23                     inputStream.close();
 24                 }
 25             } finally {
 26                 outputStream.close();
 27                 photoFile.delete();
 28             }
 29         } catch (IOException e) {
 30             result = false;
 31         }
 32         return result;
 33     }
 34 
 35     public void addContact(String name, CharSequence phoneNumber1,
 36             CharSequence phoneNumber2, String email1, String email2, String im,
 37             String nickname) {
 38         final ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
 39         ContentProviderOperation.Builder builder = null;
 40         int rawContactIndex = 0;
 41 
 42         builder = ContentProviderOperation.newInsert(RawContacts.CONTENT_URI);
 43         builder.withValue(RawContacts.ACCOUNT_NAME, "Phone contacts");
 44         builder.withValue(RawContacts.ACCOUNT_TYPE,
 45                 "com.sonyericsson.localcontacts");
 46         builder.withValue(RawContacts.AGGREGATION_MODE,
 47                 RawContacts.AGGREGATION_MODE_DISABLED);
 48         operationList.add(builder.build());
 49 
 50         // Add name.
 51         builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
 52         builder.withValueBackReference(StructuredName.RAW_CONTACT_ID,
 53                 rawContactIndex);
 54         builder.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
 55         builder.withValue(StructuredName.GIVEN_NAME, name);
 56         operationList.add(builder.build());
 57 
 58         // Add phone number.
 59         if (!TextUtils.isEmpty(phoneNumber1)) {
 60             builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
 61             builder.withValueBackReference(Phone.RAW_CONTACT_ID,
 62                     rawContactIndex);
 63             builder.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
 64             builder.withValue(Phone.TYPE, Phone.TYPE_MOBILE);
 65             builder.withValue(Phone.NUMBER, phoneNumber1);
 66             builder.withValue(Data.IS_PRIMARY, 1);
 67             operationList.add(builder.build());
 68         }
 69 
 70         // Add phone number.
 71         if (!TextUtils.isEmpty(phoneNumber2)) {
 72             builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
 73             builder.withValueBackReference(Phone.RAW_CONTACT_ID,
 74                     rawContactIndex);
 75             builder.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
 76             builder.withValue(Phone.TYPE, Phone.TYPE_HOME);
 77             builder.withValue(Phone.NUMBER, phoneNumber2);
 78             builder.withValue(Data.IS_PRIMARY, 0);
 79             operationList.add(builder.build());
 80         }
 81 
 82         // Add Email info.
 83         if (!TextUtils.isEmpty(email1)) {
 84             builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
 85             builder.withValueBackReference(Email.RAW_CONTACT_ID,
 86                     rawContactIndex);
 87             builder.withValue(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);
 88             builder.withValue(Email.TYPE, Email.TYPE_MOBILE);
 89             builder.withValue(Email.DATA, email1);
 90             operationList.add(builder.build());
 91         }
 92 
 93         if (!TextUtils.isEmpty(email2)) {
 94             builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
 95             builder.withValueBackReference(Email.RAW_CONTACT_ID,
 96                     rawContactIndex);
 97             builder.withValue(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);
 98             builder.withValue(Email.TYPE, Email.TYPE_HOME);
 99             builder.withValue(Email.DATA, email2);
100             operationList.add(builder.build());
101         }
102 
103         // Add IM info.
104         builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
105         builder.withValueBackReference(Im.RAW_CONTACT_ID, rawContactIndex);
106         builder.withValue(Data.MIMETYPE, Im.CONTENT_ITEM_TYPE);
107         builder.withValue(Im.TYPE, Im.PROTOCOL_QQ);
108         builder.withValue(Im.DATA, im);
109         operationList.add(builder.build());
110 
111         // Add Nickname info.
112         builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
113         builder.withValueBackReference(Nickname.RAW_CONTACT_ID, rawContactIndex);
114         builder.withValue(Data.MIMETYPE, Nickname.CONTENT_ITEM_TYPE);
115         builder.withValue(Nickname.TYPE, Nickname.TYPE_INITIALS);
116         builder.withValue(Nickname.DATA, nickname);
117         operationList.add(builder.build());
118 
119         try {
120             getContentResolver().applyBatch(ContactsContract.AUTHORITY,
121                     operationList);
122             // Get raw_contact_id
123             Cursor cc = getContentResolver().query(RawContacts.CONTENT_URI,
124                     null, "display_name=?", new String[] { name }, null);
125             cc.moveToFirst();
126             // Insert photo for the contact.
127             saveUpdatedPhoto(cc.getLong(cc.getColumnIndex("_id")), new File(
128                     "/sdcard/DCIM/Camera/ContactPhoto-IMG_19700104_013154.jpg"));
129         } catch (RemoteException e) {
130         } catch (OperationApplicationException e) {
131         }
132     }

基本思路是先插入除头像以外的其他信息,然后获得raw_contact_id,再给这个id插入头像,具体方法是saveUpdatedPhoto()。

Note:本人不太清楚能不能像插入姓名一样插入头像,所以才想出了这么一招,如果谁有更好的方法,不需要查询获得id就可以直接插入头像,共享一哈。

转载于:https://www.cnblogs.com/wlrhnh/p/3477216.html

Android Studio 中添加联系人需要使用内容提供器(Content Provider)来实现。下面是一个简单的示例: 1. 在 `AndroidManifest.xml` 文件中添加联系人读取和写入权限: ```xml <uses-permission android:name="android.permission.READ_CONTACTS"/> <uses-permission android:name="android.permission.WRITE_CONTACTS"/> ``` 2. 在布局文件中添加一个输入框和一个按钮: ```xml <EditText android:id="@+id/editTextName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Name"/> <Button android:id="@+id/buttonAddContact" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Add Contact"/> ``` 3. 在 Activity 中获取输入框和按钮的引用,并为按钮添加点击事件: ```java EditText editTextName = findViewById(R.id.editTextName); Button buttonAddContact = findViewById(R.id.buttonAddContact); buttonAddContact.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name = editTextName.getText().toString(); addContact(name); } }); ``` 4. 在点击事件处理函数中使用内容提供器添加联系人: ```java private void addContact(String name) { ArrayList<ContentProviderOperation> ops = new ArrayList<>(); 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.DISPLAY_NAME, name) .build()); try { getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops); Toast.makeText(this, "Contact added successfully.", Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, "Failed to add contact.", Toast.LENGTH_SHORT).show(); } } ``` 这样就可以在 Android Studio 中添加联系人了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值