通过ContentProvide取得电话本中数据,
首先根据getContentResolver方法获得一个ContentResolver对象,
然后通过气query方法查询符合标准的电话本记录,
最后将这些数据显示在textview中
下面是代码:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
TextView tv = new TextView(this);
String string = "";
super.onCreate(savedInstanceState);
//得到ContentResolver对象
ContentResolver cr = getContentResolver();
//取得电话本中开始一项的光标
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while(cursor.moveToNext()){
// 取得联系人名字
int nameFieldColumnIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
String name = cursor.getString(nameFieldColumnIndex);
string += name;
// 取得联系人ID
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
// 取得电话号码(可能存在多个号码)
while(phone.moveToNext()){
String strPhoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
string +=":" + strPhoneNumber;
}
string +="\n";
phone.close();
}
cursor.close();
tv.setText(string);
setContentView(tv);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
注意:因为要读取手机中的联系API,因此要在AndroidManifest.xml中做如下声明:
<uses-permission
android:name="android.permission.READ_CONTACTS"
/>