How to add a contact with first name and last name via intent

后端 未结 1 478
傲寒
傲寒 2021-01-04 22:26

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 i         


        
1条回答
  •  心在旅途
    2021-01-04 22:59

    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).

    0 讨论(0)
提交回复
热议问题