安卓学习笔记之获取安卓手机联系人

本人正在自学安卓编程,学到ContentProvide时,就做了如下的简单的例子,废话不多说了,献上代码. 
                //首先获得内容提供者
<pre name="code" class="java">                ContentResolver contentResolver = getContentResolver();
                //定义变量保存电话号码
                String Number=null;
                Cursor cursor= contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
		while(cursor.moveToNext()){
			//由于用到ListView,而数据适配器中的方法需要一个存储map对象的集合,所以先构造出map对象
			Map map = new HashMap<String, String>();
                        
                       int x1 = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
		    //获得联系人的名字
			String name = cursor.getString(x1);
		    map.put("name", name);
                    //以下代码为获取联系人号码的步骤,本人可是费了好大劲才解决这个问题的
                   int x2 = cursor.getColumnIndex(ContactsContract.Contacts._ID);
		 //----------------------------------------
		    String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
		    Cursor phone = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
           while(phone.moveToNext())

           {

                Number = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 

           }
        //关闭cursor对象
         phone.close();
           
           map.put("phone", Number);
			data.add(map);
       }
              <pre name="code" class="java"><pre name="code" class="java">              //关闭cursor对象
  cursor.close();listView.setVisibility(View.VISIBLE); 

//设置listview的数据适配器
 listView.setAdapter(new SimpleAdapter(this, data, R.layout.list_item ,new String[]{"name","phone"}, new int[]{R.id.name,R.id.phone}));//设置listview中每个条目的点击事件
listView.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view,int position, long id) {
//创建拨打电话的intent
 Intent intent = new Intent();intent.setAction(Intent.ACTION_CALL);String number = data.get(position).get("phone");intent.setData(Uri.parse("tel:"+number));startActivity(intent);}});
 最后别忘记添加相关权限<uses-permission android:name="android.permission.READ_CONTACTS"/> 

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


                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值