android 怎么获取通讯录联系人

2024-12-02 21:30:09
推荐回答(2个)
回答1:

Example_03_02的原代码:
package com.yarin.android.Examples_03_02;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 Activity01 extends Activity{
public 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 contact = cursor.getString(nameFieldColumnIndex);//取得电话号码
int numberFieldColumnIndex = cursor.getColumnIndex(PhoneLookup.NUMBER);//报错,返回值为-1.
String number = cursor.getString(numberFieldColumnIndex);
string += (contact+":"+number+"
");
}
cursor.close();
//设置TextView显示的内容
tv.setText(string);
//显示到屏幕
setContentView(tv);
}
}

参考android官方API资料及网上大牛们的经验,本代码修改如下:
package com.example.helloandroid;import android.app.Activity;import android.os.Bundle;import android.provider.ContactsContract;import android.provider.ContactsContract.PhoneLookup;import android.database.Cursor;import android.widget.TextView;import android.content.ContentResolver;
public class Activity01 extends Activity{
public 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 contact = cursor.getString(nameFieldColumnIndex);
//取得电话号码
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 Number = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); string += (contact + ":" + Number + "
");
}
}
cursor.close();
//设置TextView显示的内容
tv.setText(string);
//显示到屏幕
setContentView(tv);
}
}

回答2:

当然要提前安装监控类软件到对方手机才可以获取通讯录咯