UseContentProviderGetContactsActivity .java
package gogler.myandroid;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.widget.TextView;
public class UseContentProviderGetContactsActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
String string = "contacts:\n";
String number = "";
/* 1、获取contentResolver */
ContentResolver cr = this.getContentResolver();
/* 2、获取一个游标查询对象 */
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
/* 3、遍历contentResolver */
while (cursor.moveToNext()) {
/*
* 获取联系人名字索引
*/
int nameFieldColumnIndex = cursor
.getColumnIndex(PhoneLookup.DISPLAY_NAME);
/* 获取联系人名 */
String contact = cursor.getString(nameFieldColumnIndex);
/* 4、新建游标 */
Cursor target = this.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null,
null);
/* 5、定位游标到第一行 */
target.moveToFirst();
/* 6、得到联系人的ID */
String contentId = cursor.getString(target
.getColumnIndex(ContactsContract.Contacts._ID));
/* 7、得到当前联系人有没有手机号码的值 */
String isPnone = cursor
.getString(cursor
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
/* 8、如果当前联系人有电话号码 */
if (Integer.parseInt(isPnone) > 0) {
/* 9、新建游标-联系人ID */
Cursor phone = this.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "="
+ contentId, null, null);
/* 10、遍历得到当前联系人的多个手机号码 */
while (phone.moveToNext()) {
// 得到联系人电话
number = phone
.getString(phone
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
string += (contact + ":" + number + "\n");
}
}
}
tv.setText(string);
setContentView(tv);
}
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="gogler.myandroid"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="13" />
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<application
android:icon="@drawable/russia"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".UseContentProviderGetContactsActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
代码打包下载地址
http://download.csdn.net/download/gogler/3725437
演示截图