Android下实现获取本机存储的联系人
package com.demo;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
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();