欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android获取联系人示例分享

程序员文章站 2023-10-28 20:13:46
复制代码 代码如下:package com.homer.phone; import java.util.arraylist;import java.util.hashma...

复制代码 代码如下:

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" />