我需要支持
Android 2.1及更高版本.
谷歌发布了一个如何使用ContactsContract的例子,但其中一些使用了从API级别11开始可用的东西,所以我需要即兴发挥,但我被卡住了.
所以,我有这个:
String firstName = contactProperties.get("firstName"); String lastName = contactProperties.get("lastName"); String phone = contactProperties.get("phone"); String email = contactProperties.get("email"); String company = contactProperties.get("company"); String postal = contactProperties.get("street") + "," + contactProperties.get("city") + "," + contactProperties.get("state") + " " + contactProperties.get("zip") + " " + contactProperties.get("country"); // Creates a new intent for sending to the device's contacts application Intent insertIntent = new Intent(ContactsContract.Intents.Insert.ACTION); // Sets the MIME type to the one expected by the insertion activity insertIntent.setType(ContactsContract.RawContacts.CONTENT_TYPE); insertIntent.putExtra(ContactsContract.Intents.Insert.NAME,firstName + " " + lastName); insertIntent.putExtra(ContactsContract.Intents.Insert.EMAIL,email); insertIntent.putExtra(ContactsContract.Intents.Insert.PHONE,phone); insertIntent.putExtra(ContactsContract.Intents.Insert.COMPANY,company); insertIntent.putExtra(ContactsContract.Intents.Insert.POSTAL,postal); // Send out the intent to start the device's contacts app in its add contact activity. startActivity(insertIntent);
请注意我是如何构建NAME和POSTAL附加组件的.这不适用于所有设备,但是因为某些地址簿分隔了名字和姓氏字段以及city,state和zip字段.因此,我的“解决方案”看起来非常愚蠢:名字字段包含名字和姓氏,街道地址字段具有完整地址.我怎样才能解决这个问题?有人会举个例子吗?
为了记录,这不起作用:
insertIntent.putExtra(ContactsContract.CommonDataKinds.StructuredPostal.STREET,contactProperties.get("street")); insertIntent.putExtra(ContactsContract.CommonDataKinds.StructuredPostal.CITY,contactProperties.get("city"));
另请注意,我不想在清单中添加权限以允许写入联系人.这是使用Intent的重点.
解决方法
试试这个代码对我有用
String Streetname="ZZZZZ"; 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.StructuredPostal.CONTENT_ITEM_TYPE) .withValue( ContactsContract.CommonDataKinds.StructuredPostal.STREET,Streetname).build()); try { getContentResolver().applyBatch(ContactsContract.AUTHORITY,ops); } catch (Exception e) { Log.e(getApplicationContext().toString(),"Exception: " + e.getMessage()); }
添加到清单
<uses-permission android:name="android.permission.WRITE_CONTACTS"/> <uses-permission android:name="android.permission.READ_CONTACTS"/>
更多细节见这篇文章..