25

对于我的一个应用程序,我需要用户选择他现有的联系人之一或创建一个新联系人。使用以下代码显然很容易选择一个:

i = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(i, PICK_CONTACT_REQUEST );

现在我想创建一个新联系人。我尝试使用该代码,但它不会触发活动结果:

i = new Intent(Intent.ACTION_INSERT);
i.setType(Contacts.CONTENT_TYPE);
startActivityForResult(i, PICK_CONTACT_REQUEST);

上面的代码将启动联系人添加表单。然后当我验证它时,它只是要求我打开联系人列表,并且永远不会触发 onActivityResult 方法。

你能帮我让它工作吗?

我在一些板上读到这是不可能的,我必须创建自己的联系人添加表单。你能确认一下吗?

编辑:问题解决了。检查我的答案。

4

9 回答 9

52

您可以选择是否要自动添加联系人,或者使用预先填写的数据打开添加联系人活动:

/**
 * Open the add-contact screen with pre-filled info
 * 
 * @param context
 *            Activity context
 * @param person
 *            {@link Person} to add to contacts list
 */
public static void addAsContactConfirmed(final Context context, final Person person) {

    Intent intent = new Intent(Intent.ACTION_INSERT);
    intent.setType(ContactsContract.Contacts.CONTENT_TYPE);

    intent.putExtra(ContactsContract.Intents.Insert.NAME, person.name);
    intent.putExtra(ContactsContract.Intents.Insert.PHONE, person.mobile);
    intent.putExtra(ContactsContract.Intents.Insert.EMAIL, person.email);

    context.startActivity(intent);

}

/**
 * Automatically add a contact into someone's contacts list
 * 
 * @param context
 *            Activity context
 * @param person
 *            {@link Person} to add to contacts list
 */
public static void addAsContactAutomatic(final Context context, final Person person) {
    String displayName = person.name;
    String mobileNumber = person.mobile;
    String email = person.email;

    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());

    // Names
    if (displayName != null) {
        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,
                        displayName).build());
    }

    // Mobile Number
    if (mobileNumber != null) {
        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, mobileNumber)
                .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
                        ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE).build());
    }

    // Email
    if (email != null) {
        ops.add(ContentProviderOperation
                .newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Email.DATA, email)
                .withValue(ContactsContract.CommonDataKinds.Email.TYPE,
                        ContactsContract.CommonDataKinds.Email.TYPE_WORK).build());
    }

    // Asking the Contact provider to create a new contact
    try {
        context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (Exception e) {
        e.printStackTrace();
    }

    Toast.makeText(context, "Contact " + displayName + " added.", Toast.LENGTH_SHORT)
            .show();
}
于 2013-01-11T13:06:50.443 回答
18

终于找到解决办法了,分享给大家。这只是对 4.0.3 以上的 Android 版本的修复。它不适用于 4.0 到 4.0.2。

i = new Intent(Intent.ACTION_INSERT);
i.setType(Contacts.CONTENT_TYPE);
if (Integer.valueOf(Build.VERSION.SDK) > 14)
    i.putExtra("finishActivityOnSaveCompleted", true); // Fix for 4.0.3 +
startActivityForResult(i, PICK_CONTACT_REQUEST);
于 2013-01-11T13:20:54.940 回答
12
Intent intent = new Intent(
        ContactsContract.Intents.SHOW_OR_CREATE_CONTACT,
        Uri.parse("tel:" + phoneNumber));
    intent.putExtra(ContactsContract.Intents.EXTRA_FORCE_CREATE, true);
    startActivity(intent);

此代码可能会对您有所帮助。

于 2013-01-11T13:01:05.470 回答
2

我收集了各种添加联系人的 Intent。这是单个函数的结果:

@JvmStatic
fun prepareCreateContactIntent(context: Context, contactName: String? = null, phoneNumber: String? = null): Intent? {
    var intent = Intent(Intents.Insert.ACTION)
    intent.type = ContactsContract.RawContacts.CONTENT_TYPE
    val packageManager = context.packageManager
    var resolveActivity: ResolveInfo? = packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY or PackageManager.GET_RESOLVED_FILTER)
    if (resolveActivity == null) {
        intent = Intent(Intent.ACTION_INSERT).setType(ContactsContract.Contacts.CONTENT_TYPE)
        resolveActivity = packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY or PackageManager.GET_RESOLVED_FILTER)
    }
    if (resolveActivity == null) {
        intent = Intent(Intents.SHOW_OR_CREATE_CONTACT, if (phoneNumber == null) Uri.parse("tel:") else Uri.parse("tel:$phoneNumber"))
        intent.putExtra(Intents.Insert.NAME, contactName)
        resolveActivity = packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY or PackageManager.GET_RESOLVED_FILTER)
    }
    intent.putExtra(Intents.Insert.NAME, contactName)
    intent.putExtra(Intents.Insert.PHONE, phoneNumber)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
    return if (resolveActivity == null) null else intent
}

如果它返回null,则表示没有应用程序可以处理它,因此您应该自己添加它,或者向用户显示一些东西。

于 2019-08-22T14:01:52.583 回答
2

使用了已接受答案的第一部分:

        Intent i = new Intent(Intent.ACTION_INSERT);
        i.setType(ContactsContract.Contacts.CONTENT_TYPE);
        if (Build.VERSION.SDK_INT > 14)
            i.putExtra("finishActivityOnSaveCompleted", true); // Fix for 4.0.3 +
        startActivityForResult(i, 1);

现在在您的结果中,您可以获得电话号码和姓名,因为这很棘手,您应该查询两个由相同 ID 连接的不同表。我将发布这部分,以便每个人都更容易:

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (requestCode == 1) {
        if (resultCode == RESULT_OK) {
            assert data != null;
            ContentResolver cr = getContentResolver();
            Cursor cursor = cr.query(Objects.requireNonNull(data.getData()), null, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                if (cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {//Has phoneNumber
                    Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
                    while (pCur != null && pCur.moveToNext()) {
                        String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        Log.v("SteveMoretz", "NAME : " + name + " phoneNo : " + phoneNo);
                    }
                    if (pCur != null) {
                        pCur.close();
                    }
                }
            } else {
                Toast.makeText(getApplicationContext(), "User canceled adding contacts", Toast.LENGTH_SHORT).show();
            }
            if (cursor != null) {
                cursor.close();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

希望这会对某人有所帮助。

于 2019-02-05T10:37:12.790 回答
2

如果你使用 Kotlin 试试

fun Fragment.saveContact(name: String?, phone: String?) {
    if (name != null && phone != null) {
        val addContactIntent = Intent(Intent.ACTION_INSERT)
        addContactIntent.type = ContactsContract.Contacts.CONTENT_TYPE
        addContactIntent.putExtra(ContactsContract.Intents.Insert.NAME, name)
        addContactIntent.putExtra(ContactsContract.Intents.Insert.PHONE, phone)
        startActivity(addContactIntent)
    }
}
于 2018-10-11T06:17:19.807 回答
2
 // Creates a new Intent to insert a contact

Intent intent = new Intent(Intents.Insert.ACTION);
 // Sets the MIME type to match the Contacts Provider

intent.setType(ContactsContract.RawContacts.CONTENT_TYPE);

如果您已经有联系人的详细信息,例如电话号码或电子邮件地址,您可以将它们作为扩展数据插入到意图中。对于键值,请使用 Intents.Insert 中的适当常量。联系人应用程序在其插入屏幕中显示数据,允许用户进行进一步的编辑和添加。

private EditText mEmailAddress = (EditText) findViewById(R.id.email);
private EditText mPhoneNumber = (EditText) findViewById(R.id.phone);

/*
 * Inserts new data into the Intent. This data is passed to the
 * contacts app's Insert screen
 */
 // Inserts an email address

 intent.putExtra(Intents.Insert.EMAIL, mEmailAddress.getText())
 /*
  * In this example, sets the email type to be a work email.
  * You can set other email types as necessary.
  */
  .putExtra(Intents.Insert.EMAIL_TYPE, CommonDataKinds.Email.TYPE_WORK)
 // Inserts a phone number
  .putExtra(Intents.Insert.PHONE, mPhoneNumber.getText())
 /*
  * In this example, sets the phone type to be a work phone.
  * You can set other phone types as necessary.
  */
  .putExtra(Intents.Insert.PHONE_TYPE, Phone.TYPE_WORK);

创建 Intent 后,通过调用 startActivity() 发送它。

/* Sends the Intent
 */
startActivity(intent);

注意:导入“ContactsContract”的“intents”

于 2015-10-27T13:23:23.127 回答
0
 int INSERT_CONTACT_REQUEST=2;
 i = new Intent(Intent.ACTION_INSERT,Contacts.CONTENT_URI);
 startActivityForResult(i, INSERT_CONTACT_REQUEST);

protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
// TODO Auto-generated method stub
 if(requestCode == INSERT_CONTACT_REQUEST)
   {
        if (resultCode == RESULT_OK)
            {                                  
             Toast.makeText().show(getApplicationContext(),"Added_Succesfully",Toast.LENGTH_SHORT);
            }else if(resultCode == RESULT_CANCELED)
                   {
                 Toast.makeText().show(getApplicationContext(),"Contacts Adding Error",Toast.LENGTH_SHORT);     
                    }

    }
}
于 2013-01-11T13:39:10.767 回答
0

在 Xamarin.forms 和 Xamarin.Android c# 中。

Android.Content.Intent intent = new  
Android.Content.Intent(Android.Content.Intent.ActionInsert);
intent.SetType(Android.Provider.ContactsContract.Contacts.ContentType);
intent.PutExtra(Android.Provider.ContactsContract.Intents.ExtraForceCreate, 
true);
StartActivity(intent);
于 2018-04-20T07:41:29.070 回答