android读取通讯录和使用系统通讯录

时间:2024-04-17 08:03:16

第一步:注册权限

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

第二步:接收的model类

public class ContactModel {
    private String name;
    private ArrayList<String > list;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public ArrayList<String> getList() {
        return list;
    }

    public void setList(ArrayList<String> list) {
        this.list = list;
    }
}

 第三步:mian——activity

public class MainActivity extends AppCompatActivity {

    private Button button;

    private ListView listView;


    static final String TAG = "MainActivity";


    ArrayList<ContactModel>dataList = new ArrayList<ContactModel>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView)findViewById(R.id.contrcts_view);
        readContacts();


        MainAdapter adapter = new MainAdapter(this,dataList);
        listView.setAdapter(adapter);
    }


    private void readContacts(){



            Cursor cursor = null;

           try {
               cursor = this.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
                       null, null, null, null);

               int contactIdIndex = 0;
               int nameIndex = 0;

               if(cursor.getCount() > 0) {
                   contactIdIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);
                   nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
               }


               ContactModel model = null;

               while(cursor.moveToNext()) {

                   model = new ContactModel();


                   String contactId = cursor.getString(contactIdIndex);
                   String name = cursor.getString(nameIndex);
//                Log.i(TAG, contactId);
                   Log.i(TAG, "==============:" + name);

                   model.setName(name);

            /*
             * 查找该联系人的phone信息
             */
                   Cursor phones = this.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                           null,
                           ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId,
                           null, null);
                   int phoneIndex = 0;
                   if (phones.getCount() > 0) {
                       phoneIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                   }
                   ArrayList <String>list = new ArrayList<String>();
                   while (phones.moveToNext()) {




                       String phoneNumber = phones.getString(phoneIndex);
                       Log.i(TAG, "==============:" + phoneNumber);
                       list.add(phoneNumber);
                   }

                   model.setList(list);


                   dataList.add(model);
               }

           }catch (Exception e){
               Log.e(TAG,e.toString());
           }finally {
               if(cursor != null){
                   cursor.close();
               }
           }







    }







}

 第四步:adapter

public class MainAdapter extends BaseAdapter {

    private Context context;
    private List<ContactModel> list;

    public MainAdapter(Context context, List<ContactModel>list){
        this.context = context;
        this.list = list;
    }


    @Override
    public int getCount() {
        return this.list.size();
    }

    @Override
    public Object getItem(int i) {
        return this.list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {

        ViewHolder holder;
        if(view == null){
            view = LayoutInflater.from(this.context).inflate(R.layout.item_main,null);
            holder = new ViewHolder();
            holder.nameTV = (TextView)view.findViewById(R.id.name);
            holder.phoneTV = (TextView)view.findViewById(R.id.phone);
            view.setTag(holder);
        }else{
            holder = (ViewHolder)view.getTag();
        }

        ContactModel model = this.list.get(i);
        holder.nameTV.setText(model.getName());


        StringBuffer buffer = new StringBuffer();

       for (int j=0;j<model.getList().size();j++){
           if(j==0){
               buffer.append(model.getList().get(j));
           }else {
               buffer.append("\n"+model.getList().get(j));
           }
       }
        holder.phoneTV.setText(buffer.toString());



        return view;
    }


    class  ViewHolder{
        TextView nameTV;
        TextView phoneTV;
    }
}

 第五步:item 布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="tom"
        android:layout_margin="5dp"
        android:id="@+id/name"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="18580633453"
        android:layout_margin="5dp"
        android:id="@+id/phone"/>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#d6d6d6"
        />

</LinearLayout>


main的布局就一个listview,如果不会的话我需要静静了 

 

 

2.系统通讯录这里是使用fragement做的,要用startActivityForResult

   textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK,
                        ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, 1);
            }
        });

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {

            // ContentProvider展示数据类似一个单个数据库表
            // ContentResolver实例带的方法可实现找到指定的ContentProvider并获取到ContentProvider的数据
            ContentResolver reContentResolverol = getActivity(). getContentResolver();
            // URI,每个ContentProvider定义一个唯一的公开的URI,用于指定到它的数据集
            Uri contactData = data.getData();
            // 查询就是输入URI等参数,其中URI是必须的,其他是可选的,如果系统能找到URI对应的ContentProvider将返回一个Cursor对象.
            Cursor cursor = getActivity().managedQuery(contactData, null, null, null, null);
            cursor.moveToFirst();
            // 获得DATA表中的名字
            username = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

            // 条件为联系人ID
            String contactId = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.Contacts._ID));
            // 获得DATA表中的电话号码,条件为联系人ID,因为手机号码可能会有多个
            Cursor phone = reContentResolverol.query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
                            + contactId, null, null);

            while (phone.moveToNext()) {
                usernumber = phone
                        .getString(phone
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//                et_mobile.setText(usernumber + " (" + username + ")");
                toastShowShort(usernumber + " (" + username + ")");
            }

        }
    }