android获取联系人示例分享

时间:2021-05-20

复制代码 代码如下:
package com.homer.phone;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class phoneRead extends Activity {

@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);

showListView();
}

private void showListView(){
ListView listView = new ListView(this);

ArrayList<HashMap<String, String>> list = getPeopleInPhone2();
SimpleAdapter adapter = new SimpleAdapter(
this,
list,
android.R.layout.simple_list_item_2,
new String[] {"peopleName", "phoneNum"},
new int[]{android.R.id.text1, android.R.id.text2}
);
listView.setAdapter(adapter);

setContentView(listView);
}

private ArrayList<HashMap<String, String>> getPeopleInPhone2(){
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);// 获取手机联系人
while (cursor.moveToNext()) {
HashMap<String, String> map = new HashMap<String, String>();

int indexPeopleName = cursor.getColumnIndex(Phone.DISPLAY_NAME); // people name
int indexPhoneNum = cursor.getColumnIndex(Phone.NUMBER); // phone number

String strPeopleName = cursor.getString(indexPeopleName);
String strPhoneNum = cursor.getString(indexPhoneNum);

map.put("peopleName", strPeopleName);
map.put("phoneNum", strPhoneNum);
list.add(map);
}
if(!cursor.isClosed()){
cursor.close();
cursor = null;
}

return list;
}
}


记得在AndroidManifest.xml中加入android.permission.READ_CONTACTS这个permission
复制代码 代码如下:
<uses-permission android:name="android.permission.READ_CONTACTS" />

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章