安卓开发:获取手机通讯录信息

 

  写一个安卓软件,实现获取通讯录里的人名和对应的电话号码,并且通过ListView显示出来。

 

  因为要获取手机本地的信息,所以第一个步骤就是先给定权限咯

 <uses-permission android:name="android.permission.READ_CONTACTS"/>

 

 

因为获取到信息后是通过ListView显示出来,所以把布局写好,总共两个布局,一个布局放ListView,一个布局放ListView的子布局,这里比较基础,就不放代码了

 

接着就是通过java代码实现功能了

package com.contentprovide.liuliu.test_9_12_01;

import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

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

public class MainActivity extends AppCompatActivity {

ListView mylist;

List<HashMap<String, String>> list;
HashMap<String, String> hash;

Cursor cursor;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mylist = (ListView) findViewById(R.id.list);
list = new ArrayList();

// 实例化数据库指针
cursor = this.getContentResolver().
query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);

// 获取本地通讯录信息,并通过键值对的方式放进ArrayList数组中
while (cursor.moveToNext()) {

String get_name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String get_number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

hash = new HashMap<>();
hash.put("h_name", get_name);
hash.put("h_number", get_number);

list.add(hash);
}

mylist.setAdapter(new MyAdapter());

}

// 适配器
class MyAdapter extends BaseAdapter {

@Override
public int getCount() {
return list.size();
}

@Override
public Object getItem(int i) {
return i;
}

@Override
public long getItemId(int i) {
return i;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {

Myholder myholder;

if (view == null) {
view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item, null);
myholder = new Myholder();

myholder.myname = view.findViewById(R.id.name);
myholder.mynumber = view.findViewById(R.id.number);

view.setTag(myholder);

} else {

myholder = (Myholder) view.getTag();

}


myholder.myname.setText(list.get(i).get("h_name"));
myholder.mynumber.setText(list.get(i).get("h_number"));


return view;


}

class Myholder {
TextView myname;
TextView mynumber;
}
}


}

 

安卓开发:获取手机通讯录信息

上一篇:POJ3321 - Apple Tree DFS序 + 线段树或树状数组


下一篇:Android 9 的非 SDK 接口限制 | 中文教学视频