1、布局文件
<?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:id="@+id/result" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@android:color/black" android:textSize="25dp" /> </LinearLayout>
public class MainActivity extends Activity { private String[] columns = { Contacts._ID,//获得ID值 Contacts.DISPLAY_NAME,//获取姓名 Phone.NUMBER,//获得电话 Phone.CONTACT_ID }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tv = (TextView)findViewById(R.id.result); tv.setText(getQueryData());//为标签设置数据 } private String getQueryData(){ StringBuilder sb = new StringBuilder();//用于保存字符串 ContentResolver resolver = getContentResolver();//获得ContentResolver对象 Cursor cursor = resolver.query(Contacts.CONTENT_URI, null, null, null, null);//查询记录 while(cursor.moveToNext()){ int idIndex = cursor.getColumnIndex(columns[0]);//获得ID值得索引 int displayNameIndex = cursor.getColumnIndex(columns[1]);//获得姓名索引 int id = cursor.getInt(idIndex);//获得id String displayName = cursor.getString(displayNameIndex);//获得名称 Cursor phone = resolver.query(Phone.CONTENT_URI, null, columns[3]+"="+id, null, null); while(phone.moveToNext()){ int phoneNumberIndex = phone.getColumnIndex(columns[2]);//获得电话索引 String phoneNumber = phone.getString(phoneNumberIndex);//获得电话 sb.append(displayName+":"+phoneNumber+"\n");//保存数据 } } cursor.close();//关闭cursor return sb.toString(); } }
<uses-permission android:name="android.permission.READ_CONTACTS"/>