读取通讯录人员电话

一、设置权限清单

<uses-permission android:name="android.permission.READ_CONTACTS" />

二、在按钮单击中,打开通讯录

btnPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivityForResult(new Intent(Intent.ACTION_PICK,
                        ContactsContract.Contacts.CONTENT_URI), 100);
            }
        });

三、在回调事件中,监听并获取

 //接受消息
    @Override
    protected void onActivityResult(int requestCode,int resultCode,Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        TextView txtView = (TextView) findViewById(textView);
        TextView txtMsg = (TextView) findViewById(R.id.textMsg);

        txtView.setText("aaa");

        if (requestCode == 100) {
            Cursor cursor = null;
            Cursor phone = null;

            String[] projections = {
                    ContactsContract.Contacts._ID,
                    ContactsContract.Contacts.HAS_PHONE_NUMBER
            };

            cursor = getContentResolver().query(
                    data.getData(),
                    projections,
                    null,
                    null,
                null
            );

            if ((cursor == null) || (!cursor.moveToFirst())) {
                txtView.setText("cursor is null");
            } else {
                int _id = cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID);
                String id = cursor.getString(_id);
                int has_phone_number = cursor.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER);
                int hasPhoneNumber = cursor.getInt(has_phone_number);
                String phoneNumber = null;

                    if(hasPhoneNumber>0){
                        phone = getContentResolver().query(
                                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                null,
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "="
                                        + id, null, null);
                        while(phone.moveToNext()){
                            int index = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                            String number = phone.getString(index);
                            index = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
                            String strName = phone.getString(index);
                           txtView.setText(strName + " ; " + number);
                        }
                    }
                }
            }

        }


其他:


一、获取全部联系人

 //读取联系人的函数
    public void f_GetPhone(){
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String[] cols = {ContactsContract.PhoneLookup.DISPLAY_NAME,
                        ContactsContract.CommonDataKinds.Phone.NUMBER
                    };
        Cursor cursor = getContentResolver().query(uri,
                        cols,
                        null,
                        null,
                        null);
        String strOut;
        strOut = "";
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToPosition(i);
            // 取得联系人名字
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
            int numberFieldColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
            String name = cursor.getString(nameFieldColumnIndex);
            String number = cursor.getString(numberFieldColumnIndex);
            strOut += name + number;
            //Toast.makeText(this, name + " " + number, Toast.LENGTH_SHORT).show();
        }
       TextView txtOut = (TextView)findViewById(R.id.textView);
        txtOut.setText(strOut);
    }

其他地方转载收藏的相关代码


1.读取带电话号码的所有联系人。

    Android系统貌似没有直接取得带电话号码的联系人列表的功能。直接读取Contacts.CONTENT_URI只能读取联系人信息却得不到电话号码。如果先读取联系人列表,再通过联系人列表一个一个读取电话号码又非常慢,所以可以这样读:先从Phone.CONTENT_URI读取出电话列表,但是有可能一个人对应多个号码,这时只要合并一下就可以了,根据Contacts.SORT_KEY_PRIMARY排序,同一个人的不同号码是靠在一起的,这样合并就变得非常容易,坏处是对于没有电话号码的联系人这里是取不到的。(Contact是一个自定义类,这里没有写出来,这不是重点……)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
     public  static  void  loadContacts(Context context) {
         ArrayList<Contact> AllContacts =  new  ArrayList<Contact>();
         ContentResolver resolver = context.getContentResolver();
         // 要使用RawContacts.CONTACT_ID而不是Contacts.CONTACT_ID
         String[] PROJECTION = {
                 RawContacts.CONTACT_ID, Contacts.DISPLAY_NAME,
                 Contacts.LOOKUP_KEY, Contacts.PHOTO_THUMBNAIL_URI,
                 Phone.NUMBER, Phone.TYPE, Contacts.STARRED
         };
         Cursor cursor = resolver.query(Phone.CONTENT_URI, PROJECTION,  null ,
                 null , Contacts.SORT_KEY_PRIMARY);
         String preLookupKey =  "" ;
         Contact preContact =  null ;
         if  (cursor.moveToFirst()) {
             do  {
                 long  contractID = cursor.getInt( 0 );
                 String displayName = cursor.getString( 1 );
                 String lookupKey = cursor.getString( 2 );
                 String photoUri = cursor.getString( 3 );
                 boolean  starred = cursor.getInt( 6 ) ==  1 ;
                 if  (lookupKey.equals(preLookupKey) && preContact !=  null ) {
                     preContact.addPhone(cursor.getString( 4 ), cursor.getInt( 5 ));
                 else  {
                     Contact contact =  new  Contact();
                     contact.setContactId(contractID);
                     contact.setName(displayName);
                     contact.setLookupKey(lookupKey);
                     contact.setPhotoUri(photoUri);
                     contact.addPhone(cursor.getString( 4 ), cursor.getInt( 5 ));
                     contact.setStarred(starred);
                     AllContacts.add(contact);
                     preLookupKey = lookupKey;
                     preContact = contact;
                 }
             while  (cursor.moveToNext());
         else  {
             // No Phone Number Found
         }
         cursor.close();
     }

2.读取最近联系人

    Android可以通过查询Contacts.CONTENT_STREQUENT_URI得到最近联系人。注意这里得到的不是历史通话记录,而是系统根据通话频率自动获得的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public  static  void  loadStrequent() {
     ArrayList<Contact> StrequentContacts =  new  ArrayList<Contact>();
     String[] projection = { Contacts._ID, Contacts.DISPLAY_NAME,
             Contacts.LOOKUP_KEY, Contacts.PHOTO_THUMBNAIL_URI,
             Contacts.TIMES_CONTACTED, Contacts.LAST_TIME_CONTACTED,
             Contacts.STARRED, Contacts.PHOTO_ID };
     ContentResolver resolver = AppApplication.globalApplication
             .getContentResolver();
     // 显示最近联系人和收藏的联系人
     Cursor cursor = resolver.query(Contacts.CONTENT_STREQUENT_URI,
             projection,  null null null );
     // 加载最近联系人,不包括收藏的联系人
     //Cursor cursor = resolver.query(
     //  Uri.withAppendedPath(Contacts.CONTENT_URI, "frequent"),
     //  projection, null, null, null);
     while  (cursor.moveToNext()) {
         Contact contact =  new  Contact();
         long  contractID = cursor.getInt( 0 );
         String displayName = cursor.getString( 1 );
         String lookupKey = cursor.getString( 2 );
         String photoUri = cursor.getString( 3 );
         int  TIMES_CONTACTED = cursor.getInt( 4 );
         long  LAST_TIME_CONTACTED = cursor.getLong( 5 );
         boolean  starred = cursor.getInt( 6 ) ==  1 ;
         contact.setContactId(contractID);
         contact.setName(displayName);
         contact.setLookupKey(lookupKey);
         contact.setPhotoUri(photoUri);
         contact.setStarred(starred);
         contact.Times_Contacted = TIMES_CONTACTED;
         contact.Last_Time_Contacted = LAST_TIME_CONTACTED;
         StrequentContacts.add(contact);
     }
     cursor.close();
     // notify
}

3.读取合并后的通话记录。

    查询Calls.CONTENT_URI,并不能读取出具体的联系人信息,如果要知道最近通话记录,要跟已经联系人列表对照使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
     public  static  void  loadCallLogsCombined() {
         if  (AllContacts.size() ==  0 ) {
             loadContacts();
         }
         ArrayList<Contact> recentContacts =  new  ArrayList<Contact>();
         String[] projection = {
                 Calls._ID, Calls.TYPE, Calls.CACHED_NAME,
                 Calls.CACHED_NUMBER_TYPE, Calls.DATE, Calls.DURATION,
                 Calls.NUMBER
         };
         ContentResolver resolver = AppApplication.globalApplication
                 .getContentResolver();
         Cursor cursor = resolver.query(Calls.CONTENT_URI, projection,  null ,
                 null , Calls.DEFAULT_SORT_ORDER);
         while  (cursor.moveToNext()) {
             long  callID = cursor.getInt( 0 );
             int  callType = cursor.getInt( 1 );
             String name = cursor.getString( 2 );
             int  numberType = cursor.getInt( 3 );
             long  date = cursor.getLong( 4 );
             int  duration = cursor.getInt( 5 );
             String number = cursor.getString( 6 );
             if  (TextUtils.isEmpty(name)) {
                 boolean  matched =  false ;
                 for  (Iterator<Contact> iterator = recentContacts.iterator(); iterator
                         .hasNext();) {
                     Contact con = iterator.next();
                     if  (con.Last_Contact_Number.equals(number)) {
                         matched =  true ;
                         con.Times_Contacted++;
                         break ;
                     }
                 }
                 if  (!matched) {
                     Contact tmpContact =  new  Contact();
                     tmpContact.Times_Contacted =  1 ;
                     tmpContact.Last_Contact_Call_ID = callID;
                     tmpContact.Last_Contact_Call_Type = callType;
                     tmpContact.Last_Contact_Number = number;
                     tmpContact.Last_Contact_Phone_Type = numberType;
                     tmpContact.Last_Time_Contacted = date;
                     tmpContact.Last_Contact_Duration = duration;
                     recentContacts.add(tmpContact);
                 }
             else  {
                 boolean  matched =  false ;
                 for  (Iterator<Contact> iterator = recentContacts.iterator(); iterator
                         .hasNext();) {
                     Contact con = iterator.next();
                     if  (con.Last_Contact_Number.equals(number)) {
                         matched =  true ;
                         con.Times_Contacted++;
                         break ;
                     }
                 }
 
                 if  (!matched) {
                     match2:  for  (Iterator<Contact> iterator = AllContacts
                             .iterator(); iterator.hasNext();) {
                         Contact con = iterator.next();
                         ArrayList<PhoneStruct> phones = con.getPhones();
                         for  (Iterator<PhoneStruct> iterator2 = phones
                                 .iterator(); iterator2.hasNext();) {
                             PhoneStruct phoneStruct = iterator2.next();
                             if  (phoneStruct.phoneNumber.equals(number)) {
                                 matched =  true ;
                                 Contact tmpContact = con.clone();
                                 tmpContact
                                         .setPhones( new  ArrayList<Contact.PhoneStruct>());
                                 tmpContact.Times_Contacted =  1 ;
                                 tmpContact.Last_Contact_Call_ID = callID;
                                 tmpContact.Last_Contact_Call_Type = callType;
                                 tmpContact.Last_Contact_Number = number;
                                 tmpContact.Last_Contact_Phone_Type = numberType;
                                 tmpContact.Last_Time_Contacted = date;
                                 tmpContact.Last_Contact_Duration = duration;
                                 recentContacts.add(tmpContact);
                                 break  match2;
                             }
                         }
                     }
                 }
             }
         }
         cursor.close();
     }

获取联系人和电话号码

复制代码
  private void queryContactPhoneNumber() {
        String[] cols = {ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER};
        Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                cols, null, null, null);
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToPosition(i);
            // 取得联系人名字
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
            int numberFieldColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
            String name = cursor.getString(nameFieldColumnIndex);
            String number = cursor.getString(numberFieldColumnIndex);
            Toast.makeText(this, name + " " + number, Toast.LENGTH_SHORT).show();
        }
    }
复制代码

 

 根据电话号码查询联系人姓名的方法:

复制代码
public class AndroidTest extends Activity {   
    private static final String TAG = "AndroidTest";   
    
    private TextView m_TextView;   
    private EditText m_EditText;   
        
    private String mNumber;   
        
    @Override  
    public void onCreate(Bundle savedInstanceState){   
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.main);   
            
        m_TextView = (TextView) findViewById(R.id.TextView01);   
        m_EditText = (EditText) findViewById(R.id.EditText01);   
    
        m_TextView.setTextSize(20);   
        /**  
        * 设置当m_EditText中为空时提示的内容    
        * 在XML中同样可以实现:android:hint="请输入账号"  
        */  
        m_EditText.setHint("请输入账号");   
    
        /* 设置EditText事件监听 */  
        m_EditText.setOnKeyListener(new EditText.OnKeyListener() {   
        public boolean onKey(View arg0, int arg1, KeyEvent arg2)   
        {   
            // TODO Auto-generated method stub   
            // 得到文字,将其显示到TextView中   
//          m_TextView.setText("文本框中内容是:" + m_EditText.getText().toString());   
            return false;   
        }   
        });   
            
        m_EditText.setOnFocusChangeListener(new OnFocusChangeListener() {   
    
            public void onFocusChange(View v, boolean hasFocus) {   
                // TODO Auto-generated method stub   
                mNumber = ((EditText)v).getText().toString();   
                Log.d(TAG, "mNumber = " + mNumber);   
                getPeople();   
            }   
                
        });   
            
        m_EditText.addTextChangedListener(new TextWatcher() {   
    
            public void afterTextChanged(Editable s) {   
                // TODO Auto-generated method stub   
                    
            }   
    
            public void beforeTextChanged(CharSequence s, int start, int count,   
                    int after) {   
                // TODO Auto-generated method stub   
                    
            }   
    
            public void onTextChanged(CharSequence s, int start, int before,   
                    int count) {   
                // TODO Auto-generated method stub   
                // 得到文字,将其显示到TextView中   
                m_TextView.setText("文本框中内容是:" + m_EditText.getText().toString());   
            }   
                
        });   
    }   
        
    /*  
     * 根据电话号码取得联系人姓名  
     */  
    public void getPeople() {   
        String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME,   
                                ContactsContract.CommonDataKinds.Phone.NUMBER};   
    
        Log.d(TAG, "getPeople ---------");   
            
        // 将自己添加到 msPeers 中   
        Cursor cursor = this.getContentResolver().query(   
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,   
                projection,    // Which columns to return.   
                ContactsContract.CommonDataKinds.Phone.NUMBER + " = '" + mNumber + "'", // WHERE clause.   
                null,          // WHERE clause value substitution   
                null);   // Sort order.   
    
        if( cursor == null ) {   
            Log.d(TAG, "getPeople null");   
            return;   
        }   
        Log.d(TAG, "getPeople cursor.getCount() = " + cursor.getCount());   
        for( int i = 0; i < cursor.getCount(); i++ )   
        {   
            cursor.moveToPosition(i);   
                
            // 取得联系人名字   
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);      
            String name = cursor.getString(nameFieldColumnIndex);   
            Log.i("Contacts", "" + name + " .... " + nameFieldColumnIndex); // 这里提示 force close   
            m_TextView.setText("联系人姓名:" + name);   
        }   
    }   
        
}  
复制代码

 



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值