Android获取一个联系人并发短信_调用系统通讯录选择联系人代码
程序员文章站
2022-03-01 12:55:32
...
手头一项目、要坐通讯录里面选一个联系人出来、然后直接给这个联系人发短信、一拿到这个需求、头都大了、如果自己读取联系人话、会更麻烦、还不如直接打开联系人app、通过调用系统联系人的方式选择、不用自己去处理界、大概分析一下思路、先要打开通讯录的app、然后选择一个联系人、最后打开短信app把号码和内容都设置进去
一、Intent启动联系人app
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); startActivityForResult(intent, REQUEST_CODE_CONTENT);
二、onActivityResult处理号码并发送短信
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_CODE_MOBILE: if (resultCode == RESULT_OK) { Uri contactData = data.getData(); Cursor cursor = getContentResolver().query(contactData, null, null, null, null); cursor.moveToFirst(); String num = this.getContactPhone(cursor); //打开短信app Uri uri = Uri.parse("smsto:" num); Intent sendIntent = new Intent(Intent.ACTION_VIEW, uri); sendIntent.putExtra("sms_body", textShear); startActivity(sendIntent); } break; default: break; } }
三、getContactPhone代码
private String getContactPhone(Cursor cursor) { int phoneColumn = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER); int phoneNum = cursor.getInt(phoneColumn); String result = ""; if (phoneNum > 0) { // 获得联系人的ID号 int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID); String contactId = cursor.getString(idColumn); // 获得联系人电话的cursor Cursor phone = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null); if (phone.moveToFirst()) { for (; !phone.isAfterLast(); phone.moveToNext()) { int index = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); int typeindex = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE); int phone_type = phone.getInt(typeindex); String phoneNumber = phone.getString(index); result = phoneNumber; // switch (phone_type) {//此处请看下方注释 // case 2: // result = phoneNumber; // break; // // default: // break; // } } if (!phone.isClosed()) { phone.close(); } } } return result; }
四、AndroidManifest.xml添加权限
<!-- 短信相关 --> <uses-permission android:name="android.permission.SEND_SMS"></uses-permission> <uses-permission android:name="android.permission.READ_SMS"></uses-permission> <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission> <!-- 电话号码相关 --> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" />
好了、这样就可以实现在应用里面选择联系人并发送短信了、切记要添加权限不然会出错的