访问通讯录并返回号码(多个号码可以选择)

来源:互联网 发布:无间道3电影解析知乎 编辑:程序博客网 时间:2024/04/30 08:52


Intent i = new Intent(Intent.ACTION_PICK, android.provider.ContactsContract.Contacts.CONTENT_URI);startActivityForResult(i, 1);

@Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        super.onActivityResult(requestCode, resultCode, data);        if (resultCode == RESULT_OK) {            Uri contactData = data.getData();            Cursor cursor = managedQuery(contactData, null, null, null, null);            cursor.moveToFirst();            String num = this.getContactPhone(cursor);        }    }    private String getContactPhone(Cursor cursor) {        int phoneColumn = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);        int phoneNum = cursor.getInt(phoneColumn);        final List<String> result = new ArrayList<>();        position = 0;        if (phoneNum > 0) {            int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);// 获得联系人的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);                    String phoneNumber = phone.getString(index);                    result.add(phoneNumber);                }                if (!phone.isClosed()) {                    phone.close();                }            }        }        if (result.size() > 1) {//如果号码多于2个,则弹出对话框让他选择            AlertDialog.Builder builder = new AlertDialog.Builder(this);            int size = result.size();            builder.setTitle("请选择一个号码").setItems(result.toArray(new String[size]), new DialogInterface.OnClickListener() {                @Override                public void onClick(DialogInterface dialog, int which) {                    position = which;                }            }).create().show();        }        return result.get(position);    }


1 0
原创粉丝点击