您现在的位置:首页 > 博客 > Android开发 > 正文
Android下实现获取本机存储的联系人
http://www.drovik.com/      2012-9-5 12:54:37      来源:CSDN社区      点击:
public class ContentPv extends Activity {
ListView lv;
Cursor c;
    // 此处定义了将要被查询的字段列表
String[] persons = new String[]{
Contacts.People._ID,
Contacts.People.NUMBER,
Contacts.People.NAME};

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView)findViewById(R.id.lv);
ContentResolver cr = this.getContentResolver();
        // 查询指定条件的联系人,此处规定了查询条件为电话号码不为空
c = cr.query(Contacts.People.CONTENT_URI, persons, Contacts.People.NUMBER + " is not null", null, Contacts.People.DEFAULT_SORT_ORDER);
c.moveToFirst();
        // 建立Adapter并灌入ListView
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.list, c, new String[] { Contacts.People.NAME },
new int[] { R.id.TextView01 });
lv.setAdapter(adapter);
}
}

与此同时在Manifest.xml配置允许读取联系人的权限
<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>

程序运行后效果如图所示,我在ListView上添加了一个OnItemClick监听器,点击时弹出指定联系人的电话号码,代码也很简单
c.moveToPosition(position);
new AlertDialog.Builder(this)
.setTitle("Hint")
.setMessage(c.getString(c.getColumnIndexOrThrow(Contacts.People.NUMBER)))
.setPositiveButton("OK", null)
.show();
分享到:
发表评论(0)
姓名 *
评论内容 *
验证码 *图片看不清?点击重新得到验证码