Android - 显示电话簿联系人并选择一个

Posted

技术标签:

【中文标题】Android - 显示电话簿联系人并选择一个【英文标题】:Android - Showing Phonebook contacts and selecting one 【发布时间】:2012-08-20 20:07:28 【问题描述】:

我想通过单击按钮显示电话簿中的联系人列表,然后从中选择一个联系人,然后检索其联系号码?我不想制作我的自定义列表,有没有办法使用内置功能的机器人?

【问题讨论】:

【参考方案1】:

试试这个-->

   setContentView(R.layout.main);

   contactNumber = (TextView)findViewById(R.id.contactnumber);

   Button buttonPickContact = (Button)findViewById(R.id.pickcontact);
   buttonPickContact.setOnClickListener(new Button.OnClickListener()

   @Override
    public void onClick(View arg0) 
   // TODO Auto-generated method stub


   Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
   intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
   startActivityForResult(intent, 1);             


    );
   

   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

   if(requestCode == RQS_PICK_CONTACT)
   if(resultCode == RESULT_OK)
    Uri contactData = data.getData();
    Cursor cursor =  managedQuery(contactData, null, null, null, null);
    cursor.moveToFirst();

      String number =       cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));

      //contactName.setText(name);
      contactNumber.setText(number);
      //contactEmail.setText(email);
     
     
     
     

添加编辑 XML;

      <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_
       android:layout_
       android:orientation="vertical" >

      <Button
        android:id="@+id/pickcontact"
        android:layout_
        android:layout_
        android:text="Pick Contact" />

      <TextView
       android:id="@+id/contactnumber"
       android:layout_
       android:layout_ />

 </LinearLayout>

【讨论】:

@Dani 如果它对您有用,您可以选择它作为答案,以帮助将来遇到同样问题的人。 它是一个必须传递的参数。当您收到结果 Intent 时,回调会提供相同的参数,以便您的应用可以正确识别结果并确定如何处理它。您必须更改的原因是您可能使用了 PICK_CONTACT 而不是 RQS_PICK_CONTACT。将此视为您传递和返回以识别您的请求的令牌。 managedQuery() 已弃用,现在最好使用 getContentResolver().query()【参考方案2】:

我看到这个问题很老了,但是我在我的应用程序中做同样的事情,并想在这里发布我的代码,如果这对将来的任何人有帮助的话。

这是如何开始显示列表的新意图

    Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
    startActivityForResult(intent, PICK_CONTACT);

这是处理结果的方法

   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_CONTACT) 
            if (resultCode == RESULT_OK) 
                Uri contactData = data.getData();
                String number = "";
                Cursor cursor = getContentResolver().query(contactData, null, null, null, null);
                cursor.moveToFirst();
                String hasPhone = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
            String contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
            if (hasPhone.equals("1")) 
                Cursor phones = getContentResolver().query
                        (ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                        + " = " + contactId, null, null);
                while (phones.moveToNext()) 
                    number = phones.getString(phones.getColumnIndex
                   (ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll("[-() ]", "");
                
                phones.close();
    //Do something with number
             else 
                Toast.makeText(getApplicationContext(), "This contact has no phone number", Toast.LENGTH_LONG).show();
            
                cursor.close();
                
            
        
    

PICK_CONTACT 是类中定义的常量。

【讨论】:

【参考方案3】:
Intent i=new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);

startActivityForResult(i, PICK_REQUEST);

传递给您的onActivityResult() 方法的Intent 将包含所选联系人的Uri——您可以通过在该Intent 上调用getData() 来获得此信息。

Here is a sample project 演示了这一点,逻辑在保留的片段中实现,因此我们在配置更改(例如,用户旋转屏幕)时保持选定的联系人。

您也可以为此使用ACTION_GET_CONTENT,我认为这是更现代的模式,尽管ACTION_PICK 确实有效,并且是我在撰写本文时的所有示例代码。如果您将来阅读此内容(嗨,未来!),链接到的示例可能已更新为使用 ACTION_GET_CONTENT

【讨论】:

我试过了,它工作正常。但是你能帮我处理多个联系人吗?【参考方案4】:

对于 Kotlin,获取联系人的请求代码

private val REQUEST_CONTACT = 201

打算启动电话簿

 private fun fetchPhoneNo() 
        val intent = Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI)
        startActivityForResult(intent, REQUEST_CONTACT)
    

在onActivityResult中获取PhoneNo

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) 
 if (requestCode == REQUEST_CONTACT && data?.data != null) 
               val contactUri = data.data;
        val crContacts = contentResolver.query(contactUri, null, null, null, null);
        crContacts.moveToFirst()
        val id = crContacts.getString(crContacts.getColumnIndex(ContactsContract.Contacts._ID));
        if (Integer.parseInt(crContacts.getString(crContacts.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) 
            val crPhones = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                            + " = ?", arrayOf(id), null)
            crPhones.moveToFirst()
        var phoneNo = crPhones.getString(
crPhones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))                     
                crPhones.close()
            
            crContacts.close()
            
    

【讨论】:

【参考方案5】:

这是我在 API Level 29+

中尝试的工作代码

第 1 步:在 AndroidManifest.xml 中添加权限

<uses-permission android:name="android.permission.READ_CONTACTS" />

第 2 步:单击按钮时打开联系人对话框的代码

private static final int REQ_PICK_CONTACT = 3;
private static final int CONTACT_PERMISSION_CODE = 1;
//Onclick handler
public void openContacts(View view) 
    if(checkContactPermission()) 
        openContactsDialog();
     else 
        requestContactPermission();
    


//If permission is granted, then open contact box
private void openContactsDialog() 
    Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
    startActivityForResult(intent, REQ_PICK_CONTACT);


//Check if the user has the permission granted
private boolean checkContactPermission() 
    boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED;
    return result;


//Invoke request permission dialog
private void requestContactPermission() 
    String[] permission = Manifest.permission.READ_CONTACTS;
    ActivityCompat.requestPermissions(this, permission, CONTACT_PERMISSION_CODE);

//After the permission is granted, open the contact dialog
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) 
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if(requestCode == CONTACT_PERMISSION_CODE)
        if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) 
            openContactsDialog();
        
    

第 3 步:处理联系人选择

 @Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) 
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQ_PICK_CONTACT) 
        if (resultCode == RESULT_OK) 
            Cursor cursor1, cursor2;
            Uri uri = data.getData();

            cursor1 = getContentResolver().query(uri, null, null, null, null);
            if(cursor1.moveToFirst()) 
                String contactId = cursor1.getString(cursor1.getColumnIndex(ContactsContract.Contacts._ID));
                String contactName = cursor1.getString(cursor1.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                String hasNumber = cursor1.getString(cursor1.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

                if("1".equals(hasNumber)) 
                    cursor2 = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
                    while(cursor2.moveToNext()) 
                        String contactNumber = cursor2.getString(cursor2.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        //Use contactName and contactNumber for your purposes
                    
                    cursor2.close();
                
            
            cursor1.close();
            //edtName.setText(contactName);
            //edtNumber.setText(number);
        
    

解决方案:https://www.youtube.com/watch?v=1_TT3NN_g9w

【讨论】:

【参考方案6】:

在我测试过的 nexus 5x 模拟器中:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
   intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
   startActivityForResult(intent, 1);   

或:

Uri uri = Uri.parse("content://contacts");
        Intent intent = new Intent(Intent.ACTION_PICK, uri);
        intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
        startActivityForResult(intent, 1);

不适用于所有联系人。我不知道为什么。但是这个:

Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, 1);

有效。

【讨论】:

【参考方案7】:

添加PICK_CONTACT 字段:

private final int PICK_CONTACT = 55;

onCreate():

       viewPhonebook.setOnClickListener(v -> 
        try 
            Uri uri = Uri.parse("content://contacts");
            Intent intent = new Intent(Intent.ACTION_PICK, uri);
            intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
            startActivityForResult(intent, PICK_CONTACT);
         catch (Exception e) 
            e.printStackTrace();
        


    );

onActivityResult():

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) 
        switch (requestCode) 
            case PICK_CONTACT:
                     Uri contactData = data.getData();
                    Cursor cursor = managedQuery(contactData, null, null, null, null);
                    cursor.moveToFirst();
                    String number = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    edtName.setText(contactName);
                    edtNumber.setText(number);
                    break;
        
    

【讨论】:

以上是关于Android - 显示电话簿联系人并选择一个的主要内容,如果未能解决你的问题,请参考以下文章

从电话簿中获取联系人号码在android

使用 ContentProvider 从联系人获取电话号码 - Android

在 Android 中从电话簿中读取联系人

搜索联系人并从android中的电话联系人中获取联系人号码

从android中的电话簿中检索whatsapp联系人

是否可以选择特定联系人的电话号码?(Android)