main.xml仅仅是一个文本域用来展示读取来的通讯录信息:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>
AndroidManifest.xml中定义要先回的Activity,同时授予通讯录权限:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.viewcontent"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="ContentActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ContentActivity:
package com.viewcontent;
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.util.Log;
import android.widget.TextView;
public class ContentActivity extends Activity{
public void onCreate(Bundle savedInstanceState){
TextView tv = new TextView(this);
String string = "";
super.onCreate(savedInstanceState);
//得到ContentResover对象
ContentResolver cr = getContentResolver();
//取得电话本中开始一项的光标
Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
//向下移动一下光标
while(cursor.moveToNext()){
//取得联系人名字
int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
//取得电话号码
int numberFieldColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
Log.v("ViewContent", nameFieldColumnIndex+","+numberFieldColumnIndex);
String contact = cursor.getString(nameFieldColumnIndex);
String PhoneNumber = cursor.getString(numberFieldColumnIndex);
string += (contact+":"+PhoneNumber+"\n");
}
cursor.close();
//设置TextView显示的内容
tv.setText(string);
//显示到屏幕
setContentView(tv);
}
}