简体   繁体   中英

Android, create a contact at SIM programmatically

I am trying to create a contact at SIM(Nexus 5 Marshmallow).

    String name = (String)nameEditText.getText().toString();
    String phoneNumber = (String)phoneNumberEditText.getText().toString();

    String result = null;

    ArrayList<ContentProviderOperation> ops = new ArrayList < ContentProviderOperation > ();

    ops.add(ContentProviderOperation.newInsert(
            ContactsContract.RawContacts.CONTENT_URI)
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, "com.anddroid.contacts.sim")
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, "SIM")
            .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());

    ops.add(ContentProviderOperation.
            newInsert(ContactsContract.Data.CONTENT_URI)
            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
            .withValue(ContactsContract.Data.MIMETYPE,
                    ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber)
            .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
                    ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
            .build());

    // Asking the Contact provider to create a new contact
    try {
        getContentResolver().applyBatch("com.android.contacts", ops);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println(e.toString());
    }

But it creates a contact at the phone memory.

As the first applyBatch's argument i also tried "com.android.contacts" , "com.android.contacts.sim" , "content://icc/adn" . It doesn't work properly too.

Try the following code.

Uri simUri = Uri.parse("content://icc/adn");
ContentValues cv = new ContentValues();
cv.put("tag", "Me");
cv.put("number", "yourphonenumber");
getContentResolver().insert(simUri, cv);

Make sure you have required permissions granted to your application.

I came across the same question and been looking for answer.
What I do is change the ContactsContract.RawContacts.ACCOUNT_TYPE value to com.android.sim like this:

withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, "com.android.sim")

and it works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM