How to add a contact with first name and last name via intent
I am trying to launch the android native "add or edit contact" activity with some data already in the form. This is the code I am using currently:
Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
intent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
intent.putExtra(Insert.NAME, "A name");
intent.putExtra(Insert.PHONE, "123456789");
startActivity(intent);
My problem is that I would like to specify a first name and a last name. I also noticed that there is a StructuredName class which contains constant identifiers for all fields I require. Unfortunately, I was unable to add the StructuredName fields to the intent...
Does anybody know how this is done properly?
Note: I am not trying to add the contact directly, but I want to o开发者_StackOverflow社区pen a populated "add contact" dialog!
Thanks Duh
Most/all values from ContactsContract.Intents.Insert
are processed in the model/EntityModifier.java
class in the default contacts application - and that just stuffs the value from Insert.NAME
into StructuredName.GIVEN_NAME
.
You could try importing it as a vCard 2.1 (text/x-vcard), that supports all the name components but require that you either dump your vCard file on the sdcard or supply something that ContentResolver#openInputStream(Uri)
can read (typically a file on the sdcard or an URI pointing to your own ContentProvider).
A simple example that uses a ContentProvider to create the vCards dynamically:
In your Activity:
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("content://some.authority/N:Jones;Bob\nTEL:123456790\n"), "text/x-vcard");
startActivity(i);
In your ContentProvider (registered for the authority used in the ACTION_VIEW Intent):
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
try {
FileOutputStream fos = getContext().openFileOutput("filename.txt", Context.MODE_PRIVATE);
String vcard = "BEGIN:VCARD\nVERSION:2.1\n" +
uri.getPath().substring(1) +
"END:VCARD\n";
fos.write(vcard.getBytes("UTF-8"));
fos.close();
return ParcelFileDescriptor.open(new File(getContext().getFilesDir(), "filename.txt"), ParcelFileDescriptor.MODE_READ_ONLY);
} catch (IOException e) {
throw new FileNotFoundException();
}
}
This should, when triggered, insert a contact named whatever you put in the path of your Uri into the phone book. If the user has several contacts accounts he/she will be asked to select one.
Note: Proper encoding of the vCard is of course completely ignored. I image most versions of the contacts app should support vCard 3.0 also which doesn't have quite as brain-dead encoding as vCard 2.1.
On the up-side, this method will also allow you to add work/mobile and other numbers (and more).
精彩评论