内容提供者之获取联系人信息

 1 package com.example.book_provider;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import android.app.Activity;
 7 import android.database.Cursor;
 8 import android.os.Bundle;
 9 import android.provider.ContactsContract;
10 import android.view.Menu;
11 import android.view.MenuItem;
12 import android.view.View;
13 import android.view.View.OnClickListener;
14 import android.widget.Adapter;
15 import android.widget.ArrayAdapter;
16 import android.widget.Button;
17 import android.widget.ListAdapter;
18 import android.widget.ListView;
19 /**内容提供者:ContentProvider
20  * 获取联系人:需要读取联系人的权限,
21  * 需要实现数据共享就需要继承ContentProvider把数据分享出去,其他程序使用getContentResolver方法就可以对数据进行操作
22  */
23 public class MainActivity extends Activity {
24     private List<String> list=new ArrayList<String>();
25     @Override
26     protected void onCreate(Bundle savedInstanceState) {
27         super.onCreate(savedInstanceState);
28         setContentView(R.layout.activity_main);
29         ListView lv=(ListView) findViewById(R.id.listView1);//适配器的数据
30         final Button add=(Button) findViewById(R.id.button1);
31         final ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
32         lv.setAdapter(adapter);//获取内容分解器去查询数据,和SQL方法类似
33         Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, null, null, null);
34         while(cursor.moveToNext()){//游标
35             //获取联系人姓名
36             String name=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
37             //获取联系人电话号码
38             String number=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
39             list.add(name+"\n"+number);
40         }
41         if(cursor!=null)
42             cursor.close();
43         add.setOnClickListener(new OnClickListener() {
44             public void onClick(View v) {
45                 list.add("张山"+"\n"+"1234654");
46                 adapter.notifyDataSetChanged();//通知适配器数据发送改变
47             }
48         });
49     
50     }
51 }

XML文件

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3     package="com.example.book_provider"
 4     android:versionCode="1"
 5     android:versionName="1.0" >
 6 
 7     <uses-sdk
 8         android:minSdkVersion="15"
 9         android:targetSdkVersion="15" />
10 
11     <application
12         android:allowBackup="true"
13         android:icon="@drawable/ic_launcher"
14         android:label="@string/app_name"
15         android:theme="@style/AppTheme" >
16         <activity
17             android:name=".MainActivity"
18             android:label="@string/app_name" >
19             <intent-filter>
20                 <action android:name="android.intent.action.MAIN" />
21 
22                 <category android:name="android.intent.category.LAUNCHER" />
23             </intent-filter>
24         </activity>
25     </application>
26     <!-- 获取联系人的权限 -->
27     <uses-permission android:name="android.permission.READ_CONTACTS"/>
28     
29 </manifest>

 获取联系人信息:包括邮箱

//读取联系人的权限:<uses-permission android:name="android.permission.READ_CONTACTS"/>
public class MainActivity extends Activity {
    
    private ContentResolver contentResolver;
    
    /**
     *管理联系人的uri
     */
    private  Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;
    
    private Uri phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;// 管理联系人的电话的Uri
    
    private Uri emailUri = ContactsContract.CommonDataKinds.Email.CONTENT_URI;// 管理联系人的Email的Uri

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //获取contentResolver对象操作数据库
        contentResolver = getContentResolver();
        
        //获得数据
        List<Contact> data = getContactsDatalist();
        for (Contact contact : data) {
            System.out.println(contact);
        }
    }
    
    
    public List<Contact> getContactsDatalist(){
        ArrayList<Contact> dataList = new ArrayList<Contact>();
        //先查出所有的联系人--得到姓名和_id
        //根据_id去查询联系人的电话号码
        //根据_id再去查询联系人的email
        
        Cursor cursorContracts = contentResolver.query(contactsUri, new String[]{ContactsContract.Contacts._ID,ContactsContract.Contacts.DISPLAY_NAME}, null, null, null);
        Contact contact;
        while(cursorContracts.moveToNext()){
            contact = new Contact();
            int _id  = cursorContracts.getInt(cursorContracts.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cursorContracts.getString(cursorContracts.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            contact.set_id(_id);
            contact.setName(name);
            
            //根据_id去查询联系人的电话号码
            Cursor cursorPhone = contentResolver.query(phoneUri, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER}, ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID + " = ?", new String[]{_id + ""}, null);
            while(cursorPhone.moveToNext()){
                String phone = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                contact.setPhone(phone);
            }
            //根据_id再去查询联系人的email
            Cursor cursorEmail= contentResolver.query(emailUri, new String[]{ContactsContract.CommonDataKinds.Email.DATA}, ContactsContract.CommonDataKinds.Email.RAW_CONTACT_ID + " = ?", new String[]{_id + ""}, null);
            while(cursorEmail.moveToNext()){
                String email = cursorEmail.getString(cursorEmail.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                contact.setEmail(email);
            }
            dataList.add(contact);
        }
        return dataList;
    }
}

 

2.跳转到联系人界面,并获取选择的联系人信息

//需要权限:<uses-permission android:name="android.permission.READ_CONTACTS"/> 跳转到联系人界面
startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 0);


@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == 0) {
            ContentResolver reContentResolverol = getContentResolver();
            Uri contactData = data.getData();
            Cursor cursor = managedQuery(contactData, null, null, null, null);
            if(cursor != null){
                cursor.moveToFirst();
                String username = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                Log.e("tag","用户名="+username);
                String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                Cursor phone = reContentResolverol.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId,
                        null,
                        null);
                //当一个人有多个号码的时候
                while (phone.moveToNext()) {
                    String usernumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    String userName = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    Log.e("tag","手机号="+usernumber + ",用户名="+userName);
                }
                phone.close();
            }else{
                //也许点击的是文件管理器
                Log.e("tag","联系人信息获取失败,获取的文件路径:" + contactData.getPath());
            }
        }
    }
 

 

posted @ 2016-04-15 16:51  ts-android  阅读(672)  评论(0编辑  收藏  举报