本人正在自学安卓编程,学到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"/>