你的位置:首页 > 操作系统

[操作系统]andriod 读取通讯录


package com.example.yanlei.wifi;

import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

private ListView lvContacts=null;
private Cursor cursor=null;
private Button btnRead=null;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = new TextView(this);
String str = "";
// 得到contentresolver对象
ContentResolver cr = getContentResolver();
// 取得电话本中开始一项的光标,必须先moveToNext()
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
while (cursor.moveToNext())
{
//取得联系人的名字索引
int nameIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
String contact = cursor.getString(nameIndex);
str += (contact + ":" + "\n");
//取得联系人的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));
str += (strPhoneNumber + "\n");
Log.i("TAG","phoneNumber:"+strPhoneNumber+"contact"+contact);
}
phone.close();
}
cursor.close();
tv.setText(str);
setContentView(tv);

}



}