所需要的权限申请
<!-- 打电话权限 --> <uses-permission android:name="android.permission.CALL_PHONE" /> <!-- 读取通讯录的权限 --> <uses-permission android:name="android.permission.WRITE_CONTACTS" /> <uses-permission android:name="android.permission.READ_CONTACTS" />
本文主要讲点击“从通讯录添加”跳转到系统的通讯录,点击其中一条通讯录返回界面并读取数据:姓名+号码。
/*跳转到系统通讯录里获取号码*/
private void addNumber() {
startActivityForResult(new Intent(
Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 1);
}
用户点击通讯录后,返回的数据
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
ContentResolver reContentResolverol = getContentResolver();
Uri contactData = data.getData();
@SuppressWarnings("deprecation")
Cursor cursor = managedQuery(contactData, null, null, null, null);
cursor.moveToFirst();
String username = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor phone = reContentResolverol.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId,
null,
null);
while (phone.moveToNext()) {
String usernumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Logs.i("用户名:" + username + " 电话号码:" + usernumber + " id: " + contactId);
et.setText(usernumber.replace(" ", ""));
}
}
}
打电话操作
/*打电话操作*/ private void callPhone() { try { /*跳过拨号界面,直接拨打电话*/ Uri uri = Uri.parse("tel:" + getString(R.string.phone)); Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(uri); /*只调用拨号界面,不拨出电话*/ // Intent intent = new Intent(Intent.ACTION_DIAL); // intent.setData(uri); startActivity(intent); } catch (Exception e) { LogUtils.e("打电话错误原因:"+e); } }