android之實現跳轉手機通訊錄獲取指定姓名和手機號碼

weixin_34148340發表於2019-02-11

實現跳轉手機通訊錄獲取指定姓名和手機號碼

1、先新增許可權

 <!-- 讀聯絡人許可權 -->
<uses-permission android:name="android.permission.READ_CONTACTS" />
<!--用於讀取手機當前的狀態-->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

如果是android系統是6.0之後的,需要在程式碼中動態新增許可權

 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        int hasWriteContactsPermission = checkSelfPermission(Manifest.permission.READ_CONTACTS);
        if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]{Manifest.permission.WRITE_CONTACTS},REQUEST_CODE_ASK_PERMISSIONS);
            return;
        }
    }

2、點選跳轉實現

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

3、在返回頁面重寫onActivityResult()方法

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(data==null)
    {
        return;
    }

    if(requestCode==0) {
           /* **//*/處理返回的data,獲取選擇的聯絡人資訊***/
        Uri uri = data.getData();
        String[] contacts = getPhoneContacts(uri);

        LogHelper.d(TAG,"------contacts--"+contacts[0]);//列印出的姓名
        LogHelper.d(TAG,"------contacts--"+contacts[1]);//列印出來的電話

        addGoodsName.setText(contacts[0]);
        addGoodsPhone.setText(contacts[1]);

    }
}

上面實現獲取姓名電話的方法getPhoneContacts()如下

private String[] getPhoneContacts(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);
        //取得電話號碼**
        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);
        if(phone != null){
            phone.moveToFirst();
            contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        }
        phone.close();
        cursor.close();
    }
    else
    {
        return null;
    }
    return contact;
}

由此就可以獲取通訊錄中的姓名和電話了

相關文章