获取手机联系人的信息

使用ContentResolver获取手机联系人的办法,建议使用第二种

1.一般下面的方法查询的是视图的表,表的字段需要查询获取,比较麻烦,可能会经常出错(特别在真机调试的时候)

// TODO 这种方法直接指定uri在真机中是获取不到联系人信息的
                // [1]获取到内容解析者
//                ContentResolver contentResolver = getContentResolver();
                /*Cursor cursor = contentResolver.query(Uri
                        .parse("content://com.android.contacts/raw_contacts"),
                        new String[] { "contact_id" }, null, null, null);
                while (cursor.moveToNext()) {// 有内容,进行获取
                    //[2]获取到contact_id
                    String contact_id = cursor.getString(0);
                    //[3]根据获取到的contact_id进行查询data表中的数据,data1,mimetype_id字段数据
                    //##虽然data表中的字段是mimetype_id,但是要使用mimetype才可以获取到数据,对应的是mimetypes表的字段
                    Cursor cursor2 = contentResolver.query(
                            Uri.parse("content://com.android.contacts/data"),
                            new String[] { "data1", "mimetype" },
                            "raw_contact_id=?", new String[] { contact_id }, null);

                    //创建集合HashMap,用来存储联系人的姓名和号码,对ListView进行填充数据
                    HashMap<String, String> contactsMap=new HashMap<String, String>();
                    while (cursor2.moveToNext()) {
                        //[4]获取到data1,mimetype_id
                        String data1 = cursor2.getString(0);
                        String type = cursor2.getString(1);
                        if (type.equals("vnd.android.cursor.item/phone_v2")) {//data1是电话号码
                            //将数据进行保存
                            if (!TextUtils.isEmpty(data1)) {
                                contactsMap.put("phone", data1);
                            }else{
                                contactsMap.put("phone", "null");//要是为空的话
                            }
                        }else if(type.equals("vnd.android.cursor.item/name")){//data1联系人名字
                            if (!TextUtils.isEmpty(data1)) {
                                contactsMap.put("name", data1);
                            }else{
                                contactsMap.put("name", "null");//要是为空的话
                            }
                        }
                    }
                    //循环一次添加一组联系人的数据
                    contactsList.add(contactsMap);
                }*/

2.直接使用API提供封装好的类ContactsContract进行URI和字段的获取会简单点,一般不容易出错,在真机中调试比较好用

          ContentResolver contentResolver = getContentResolver();
                Cursor cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        new String[]{
                            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                            ContactsContract.CommonDataKinds.Phone.DATA1
                        },
                        null, null, null);
                while (cursor.moveToNext()) {
                    HashMap<String, String> hashMap=new HashMap<String, String>();
                    hashMap.put("name", cursor.getString(0));
                    hashMap.put("phone", cursor.getString(1));
//                    Log.i("phone", cursor.getString(0));
//                    Log.i("phone", cursor.getString(1));
                    contactsList.add(hashMap);
                }

下面是整个Activity代码:

package com.itlearn.contacts;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {
    private ListView lv_contacts;
    //存储联系人信息(存储在Map集合中(姓名和号码))的单列集合
    ArrayList<HashMap<String,String>> mContactsArrayList=new ArrayList<HashMap<String,String>>();

    public Handler mHandler=new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            lv_contacts.setAdapter(new ListContactsAdapter());
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv_contacts = (ListView) findViewById(R.id.lv_contacts);
        initUI();
    }

    private void initUI() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                ContentResolver contentResolver = getContentResolver();
                Cursor cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        new String[]{
                            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                            ContactsContract.CommonDataKinds.Phone.DATA1
                        },
                        null, null, null);
                while (cursor.moveToNext()) {
                    HashMap<String, String> hashMap=new HashMap<String, String>();
                    hashMap.put("name", cursor.getString(0));
                    hashMap.put("phonenumber", cursor.getString(1));
//                    Log.i("phone", cursor.getString(0));
//                    Log.i("phone", cursor.getString(1));
                    mContactsArrayList.add(hashMap);
                }
                //发送消息进行UI更新
                mHandler.sendEmptyMessage(0);
            }
        }).start();
    }

    private class ListContactsAdapter extends BaseAdapter{

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

        @Override
        public HashMap<String,String> getItem(int position) {
            return mContactsArrayList.get(position);
        }

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(getApplicationContext(), R.layout.listview_contact_item, null);
            //获取到布局中需要显示name和phonenumber的id
            TextView tv_name=(TextView) view.findViewById(R.id.tv_name);
            TextView tv_phonenumber=(TextView) view.findViewById(R.id.tv_phonenumber);

            tv_name.setText(getItem(position).get("name"));
            tv_phonenumber.setText(getItem(position).get("phonenumber").replace(" ", "").replace("-", "").trim());
            return view;
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

布局文件:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.itlearn.contacts.MainActivity" >

    <TextView
        android:id="@+id/tv_title"
        android:text="联系人列表"
        android:textSize="20sp"
        android:textColor="#FFF"
        android:padding="15sp"
        android:background="#222222"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <!-- 联系人列表显示 -->
    <ListView
        android:id="@+id/lv_contacts"
        android:layout_below="@+id/tv_title"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>

</RelativeLayout>

listview_contacts_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="match_parent"
    android:padding="10dp"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_name"
        android:textColor="#23350B"
        android:textSize="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/tv_phonenumber"
        android:paddingTop="3dp"
        android:paddingBottom="1dp"
        android:textColor="#C3010A"
        android:textSize="16dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

运行结果:

时间: 2024-08-25 22:10:27

获取手机联系人的信息的相关文章

Android获取手机联系人的姓名和电话

Android获取手机联系人的姓名和电话 主要是用到了跳入手机联系人的intent和获取手机联系人信息的内容提供者,直接上代码 注:此贴是借鉴别人的帖子加了一些自己的东西写出的,原帖地址明日附上: / 首先 我们需要跳入手机通讯录 Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); startActivityForResult(intent, 0); // 之后,我们需要重写

[小项目] 获取手机联系人并且向服务器发送JSON数据

[小项目] 获取手机联系人并且向服务器发送JSON数据 好久没有写文档了...最近忙着带班,也没有时间学习新东西,今天刚好有个小Demo,就写了一下,顺便丰富一下我的博客吧! 首先说一下需求: 简单的说,就是一个程序,会获取手机的联系人列表,然后转换成JSON字符串数组,向指定服务器中发送数据...总感觉有侵犯别人隐私权的意味; 注:仅供学习使用,不要做违法的事情哟 这个程序我写的有点有条理,首先有几个工具类: 1. 判断是否联网的工具类(NetUtils) 2. 从手机中获取所有联系人的工具类

Android_获取手机各种详细信息

TelephonyManager类主要提供了一系列用于访问与手机通讯相关的状态和信息的get方法.其中包括手机SIM的状态和信息.电信网络的状态及手机用户的信息.在应用程序中可以使用这些get方法获取相关数据. TelephonyManager类的对象可以通过Context.getSystemService(Context.TELEPHONY_SERVICE)方法来获得,需要注意的是有些通讯信息的获取对应用程序的权限有一定的限制,在开发的时候需要为其添加相应的权限. 以下列出TelephonyM

Android开发之获取手机SIM卡信息

TelephonyManager是一个管理手机通话状态.电话网络信息的服务类.该类提供了大量的getXxx(),方法获取电话网络的相关信息. TelephonyManager类概述: 可用于訪问有关设备上的电话服务信息. 应用程序能够使用这个类的方法来确定电话服务和状态,以及訪问某些类型的用户信息.应用程序还能够注冊一个侦听器以接收的电话状态变化通知. 你不能直接实例化这个类;相反,你能够通过Context.getSystemService(Context.TELEPHONY_SERVICE)方

获取手机联系人,并通过拼音字母快速查询

获取手机联系人,并通过拼音字母快速查询. 通过工具类转换联系人首字的首字母,并排序显示. 通过画布的方式在布局右侧添加快速查询的字母布局 显示效果如下图: 右侧点击[★]时回到顶部: 滑动到[N]时N开头的联系人置顶 代码: 通过画布的方式在布局右侧添加快速查询的字母布局 http://download.csdn.net/detail/zengchao2013/8750259 欢迎指正~ 通过画布的方式在布局右侧添加快速查询的字母布局

ios 获取手机相关的信息

获取手机信息      应用程序的名称和版本号等信息都保存在mainBundle的一个字典中,用下面代码可以取出来 //获取版本号 NSDictionary *infoDict = [[NSBundle mainBundle]infoDictionary]; NSString *versionNum = [infoDict objectForKey:@"CFBundleVersion"];//版本号 NSString *appName = [infoDict objectForKey:

Android简易实战教程--第十一话《获取手机所有应用信息Engine类详解》

如果想要获取系统手机应用的详细信息,那么下边代码可以直接作为模板使用.笔者对每一行代码都做了注解,供您参考.直接上代码: package com.example.itydl.engines; import java.io.File; import java.util.ArrayList; import java.util.List; import com.example.itydl.domain.AppBean; import android.content.Context; import an

stackflow看到的获取手机联系人 contact 的代码

package com.john.mobilesafe.activity.naviactivity; import android.content.ContentResolver; import android.database.Cursor; import android.os.Bundle; import android.provider.ContactsContract; import android.support.v7.app.AppCompatActivity; import com

获取手机安装包信息+运行应用信息

1 PacInfo pacInfo=new PacInfo(); 2 ArrayList<AppInfo> appInfos=pacInfo.Get(SysInfoService.this); 3 StringBuffer stringBuffer=new StringBuffer(); 4 stringBuffer.append("\n\n"+"日记时间:"+FileStore.date()); 5 stringBuffer.append("