如何从Intent中选择电话簿中的电话号码

时间:2014-07-06 21:17:46

标签: android android-intent android-contacts

我知道获取电话号码的意图

Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, GET_CONTACT_NUMBER);

但我不知道如何在未请求onActivityResult()的联系读取权限的情况下获取电话号码。

感谢。

2 个答案:

答案 0 :(得分:0)

尝试使用

替换代码
Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);

答案 1 :(得分:0)

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request it is that we're responding to
    if (requestCode == GET_CONTACT_NUMBER) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            // Get the URI that points to the selected contact
            Uri contactUri = data.getData();
            // We only need the NUMBER column, because there will be only one row in the result
            String[] projection = {Phone.NUMBER};

            // Perform the query on the contact to get the NUMBER column
            // We don't need a selection or sort order (there's only one result for the given URI)
            // CAUTION: The query() method should be called from a separate thread to avoid blocking
            // your app's UI thread. (For simplicity of the sample, this code doesn't do that.)
            // Consider using CursorLoader to perform the query.
            Cursor cursor = getContentResolver()
                    .query(contactUri, projection, null, null, null);
            cursor.moveToFirst();

            // Retrieve the phone number from the NUMBER column
            int column = cursor.getColumnIndex(Phone.NUMBER);
            String number = cursor.getString(column);

            // Do something with the phone number...
        }
    }
}
  

注意:在Android 2.3(API级别9)之前,执行查询   联系人提供商(如上所示)需要您的应用   声明READ_CONTACTS权限(请参阅安全性和权限)。   但是,从Android 2.3开始,Contacts / People应用程序授予   您的应用程序是从联系人提供程序读取的临时权限   当它返回结果时。临时权限仅适用于   请求的具体联系人,所以你不能查询其他联系人   比意图的Uri指定的那个,除非你确实声明了   READ_CONTACTS权限。

来源:http://developer.android.com/training/basics/intents/result.html