美文网首页
Android获取系统联系人

Android获取系统联系人

作者: lxbnjupt | 来源:发表于2017-04-23 22:44 被阅读0次

    1.在AndroidManifest中加入读写权限

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

    2.Android系统管理联系人的URI

    获取联系人的ID和NAME:ContactsContract.Contacts.CONTENT_URI
    获取联系人的电话号码:ContactsContract.CommonDataKinds.Phone.CONTENT_URI
    获取联系人的邮箱地址:ContactsContract.CommonDataKinds.Email.CONTENT_URI
    (注:Contacts有两个表,分别是rawContact和Data,rawContact记录了用户的id和name,其中id栏名称为:ContactsContract.Contacts._ID, name名称栏为ContactContract.Contracts.DISPLAY_NAME,电话信息表的外键id为ContactsContract.CommonDataKinds.Phone.CONTACT_ID,电话号码栏名称为:ContactsContract.CommonDataKinds.Phone.NUMBER.

    3.调用系统联系人获取电话号码

        Intent intent = new Intent(Intent.ACTION_PICK,
               ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
        startActivityForResult(intent, 0);
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if(requestCode == 0) {
                String phoneNumber = "";
                if(data != null) {
                    Uri uri = data.getData();
                    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
                    if (null != cursor && cursor.moveToFirst()){
                        phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        //得到纯数字电话号码
                        if (phoneNumber.startsWith("+86")) {
                            phoneNumber = phoneNumber.replace("+86", "");
                        }
                        phoneNumber = phoneNumber.replace(" ", "");
                        phoneNumber = phoneNumber.replace("-", "");
                        editText.setText(phoneNumber);
                        cursor.close();
                    }
                }
            }
        }
    

    相关文章

      网友评论

          本文标题:Android获取系统联系人

          本文链接:https://www.haomeiwen.com/subject/hqxuzttx.html