App 获取本地姓名和号码

在项目开发中,经常打开联系人获取用户的姓名和手机号,在这里记录下:

一、创建方法,点击打开联系人界面:

private void openPhone(){
    Intent intent = new Intent(Intent.ACTION_PICK,
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
    startActivityForResult(intent, 100);
}

二、获取联系人后

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 100) {
        if (resultCode==RESULT_OK){
            if (data!=null){
                Uri uri=data.getData();
                String[] contact=getPhone(uri);
                try {
                    String name = contact[0];
                    String phone = formatPhoneNum(contact[1]);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

其中getPhone()方法:

/** 读取联系人信息 */
private String[] getPhone(Uri uri){
    String[] contact = new String[2];
    /** 得到ContentResolver对象 */
    ContentResolver cr = getContentResolver();
    Cursor cursor = cr.query(uri, null, null, null, null);
    if (cursor != null&&cursor.moveToFirst()) {
        /** 取得联系人姓名 */
        int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
        contact[0] = cursor.getString(nameFieldColumnIndex);
        contact[1]=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        cursor.close();
    } else {
        return null;
    }
    return contact;
}

   formatPhoneNum()方法:

/** 去掉手机号内除数字外的所有字符 */
private String formatPhoneNum(String phoneNum) {
    String regex = "(\\+86)|[^0-9]";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(phoneNum);
    return matcher.replaceAll("");
}

你可能感兴趣的:(运维自动化)