android獲取聯絡人示例分享

NO IMAGE

複製程式碼 程式碼如下:
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” />

您可能感興趣的文章:

Android ContentProvider實現獲取手機聯絡人功能Android獲取手機通訊錄、sim卡聯絡人及呼叫撥號介面方法Android 獲取手機聯絡人例項程式碼詳解Android程式設計操作聯絡人的方法(查詢,獲取,新增等)Android獲取聯絡人頭像的方法Android獲取手機聯絡人資訊Android獲取手機聯絡人電話號碼並返回結果Android獲取聯絡人姓名和電話程式碼Android實現獲取聯絡人電話號碼功能android如何獲取聯絡人所有資訊