Android内容提供者(一)读取系统联系人
2016-06-23 13:56
525 查看
想要读取系统的联系人,必须先获取权限。
1.创建工程ReadContacts,在清单文件中添加读取联系人的权限。
2.修改主布局,添加用来显示数据的listview
3.创建代码,读取系统联系人(如果是模拟器的话,先在联系人中随便添加几个)
运行程序,启动模拟器,就可以看到手机中保存联系人的姓名和电话号码了。
1.创建工程ReadContacts,在清单文件中添加读取联系人的权限。
<uses-permission android:name="android.permission.READ_CONTACTS" />
2.修改主布局,添加用来显示数据的listview
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ListView android:id="@+id/contacts_list_view" android:layout_width="match_parent" android:layout_height="wrap_content" > </ListView> </LinearLayout>
3.创建代码,读取系统联系人(如果是模拟器的话,先在联系人中随便添加几个)
public class MainActivity extends Activity { private ListView mContactsLV; private ArrayAdapter<String> mAdapter; private List<String> mContactsList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContactsLV = (ListView) findViewById(R.id.contacts_list_view); mContactsList = new ArrayList<String>(); Cursor cursor = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); while (cursor.moveToNext()) { String name = cursor .getString(cursor .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); String number = cursor .getString(cursor .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); mContactsList.add(name + "\n" + number); } if (cursor != null) { cursor.close(); } mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mContactsList); mContactsLV.setAdapter(mAdapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
运行程序,启动模拟器,就可以看到手机中保存联系人的姓名和电话号码了。
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories