android获取手机通讯录

package com.zking.getcontact;  

import android.content.ContentResolver;  
import android.database.Cursor;  
import android.net.Uri;  
import android.support.v7.app.AppCompatActivity;  
import android.os.Bundle;  
import android.util.Log;  

public class MainActivity extends AppCompatActivity {  

    private ContentResolver contentResolver;  

    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
          //获取内容访问者
        contentResolver = getContentResolver();  
        //拿到所有通讯录的姓名
        Uri uri=Uri.parse("content://com.android.contacts/raw_contacts");  
        Cursor cursor=contentResolver.query(uri,null,null,null,null);  
        while(cursor.moveToNext()){  
            String _id=cursor.getString(cursor.getColumnIndex("_id"));  //拿到id
            String display_name=cursor.getString(cursor.getColumnIndex("display_name"));  //拿到姓名
            Log.i("test",""+_id+"\t\t\t"+display_name);  

            Uri  uriData=Uri.parse("content://com.android.contacts/raw_contacts/"+_id+"/data");  //根据id拿到这个对象的所有信息
            Cursor contactsInfo=contentResolver.query(uriData,null,null,null,null);  
            while (contactsInfo.moveToNext()){  
                String mimetype=contactsInfo.getString(contactsInfo.getColumnIndex("mimetype"));  
                String data1=contactsInfo.getString(contactsInfo.getColumnIndex("data1"));  

                if("vnd.android.cursor.item/phone_v2".equals(mimetype)){  
                    Log.i("test",""+mimetype+"\t\t\t"+data1);  
                }  
            }  

        }  
    }  
}  

xml配置设为可访问状态:

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

你可能感兴趣的:(android获取手机通讯录)