Android获取手机联系人姓名+手机号码

2023-08-25 14:11:55 浏览数 (1)

1、首先添加权限

代码语言:javascript复制
<!-- 读取联系人权限 -->
  <uses-permission   android:name="android.permission.READ_CONTACTS"/>

2、获取代码

代码语言:javascript复制
new Thread(new Runnable() {
            @Override
            public void run() {
                //得到ContentResolver对象
                ContentResolver cr = getContentResolver();
                //取得电话本中开始一项的光标
                Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
                //向下移动光标
                String linStr = "";
                while (cursor.moveToNext()) {
                    //取得联系人名字
                    int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
                    String contact = cursor.getString(nameFieldColumnIndex);
                    //取得电话号码
                    String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                    Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID   "="   ContactId, null, null);
 
                    while (phone.moveToNext()) {
                        String PhoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        //格式化手机号
                        PhoneNumber = PhoneNumber.replace(" ", "");
                        if (PhoneNumber.length() == 11)
                            linStr = linStr   PhoneNumber   ",";
                    }
                }
                String allStr = "";
                if (EmptyUtils.isNotEmpty(linStr))
                    allStr = linStr.substring(0, linStr.length() - 1);
                else
                    allStr = linStr;
 
                final String phones = allStr;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        L.e("111", phones);
                    }
                });
            }
        }).start(); 

万事大吉。

0 人点赞