敢说敢作敢为, 无怨无恨无悔。这篇文章主要讲述安卓基础之读取联系人的姓名和电话相关的知识,希望能为你提供帮助。
一.摘要:利用内容解释器调用联系人应用的内容提供者暴露的方法,读取联系人信息.(本节只总结实现步骤,解释请看http://www.xuanyusong.com/archives/169)
二.主要逻辑:
1.获取内容解释者mResolver
ContentResolver mResolver=getApplicationContext().getContentResolver();
【安卓基础之读取联系人的姓名和电话】2.调用解释者的query方法获取cursor
Cursor cursor=mResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,projection,null,null,null);
3.遍历cursor获得联系人信息
if(cursor!=null){ while(cursor.moveToNext()){ ...... } }
三.具体实现:
androidManifest需要加入权限:
< uses-permission android:name="android.permission.READ_CONTACTS"> < /uses-permission> < uses-permission android:name="android.permission.WRITE_CONTACTS"> < /uses-permission>
MainActivity.java
public class MainActivity extends AppCompatActivity {String[] projection=new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); List< Contract> mContracts=new ArrayList< Contract> (); mContracts=getcontract(); if(mContracts!=null){ for (Contract contract:mContracts) { int id=contract.getId(); String name=contract.getName(); String phone=contract.getPhone(); System.out.println(id+name+phone); }} } private List< Contract> getcontract(){List< Contract> contracts=new ArrayList< Contract> (); ContentResolver mResolver=getApplicationContext().getContentResolver(); Cursor cursor=mResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,projection,null,null,null); if(cursor!=null){ while(cursor.moveToNext()){ String phone =cursor.getString(2); int id=cursor.getInt(0); String name=cursor.getString(1); Contract contract=new Contract(); contract.setId(id); contract.setName(name); contract.setPhone(phone); contracts.add(contract); } } return contracts; } }
Contract.java
public class Contract { int id=0; String name=null; String phone=null; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public int getId() { return id; } public void setId(int id) { this.id = id; }}
推荐阅读
- Server.MapPath是使用
- 安卓 通过www读取Application.persistentDataPath
- Android 如何将手机屏幕投屏到PC端
- 项目初始化以后出现(Unable to load script from assets 'index.android.bundle)
- Spring08-----IoC容器ApplicationContext
- Unexpected directive 'XXX' imported by the module 'AppMoode'
- Android VideoView播放网络视频简介(转)
- mapper.xml文件中标签没有提示的解决
- 解决Android Studio无法下载sdk的问题