访问手机通讯录
1.在AndroidManifest.xml设置访问通讯的权限:
//添加访问通讯录的权限
<uses-permission android:name="android.permission.READ_CONTACTS"/>
2.模拟获取通讯录的名称与电话号码,然后用ListView进行显示,现在xml文件中添加ListView,
<ListView android:id="@+id/contact_listview" android:layout_width="match_parent" android:layout_height="match_parent" ></ListView>
3.在Activity中,配置ListView(核心代码)
private ListView listView; private ArrayAdapter<String> adapter; //适配器 List<String> contactList = new ArrayList<String>(); //通讯获取的数据 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView)findViewById(R.id.contact_listview); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contactList); listView.setAdapter(adapter); /*获取通讯录数据 * 1.先判断是否已经有读取通讯录的权限 * 2.如果没有的话,询问用户,如果有的话,直接读取通讯录的数据*/ //1 if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED ) { //未获得权限,询问用户 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 1); } else { //已经权限 readContacts(); } } //读取通讯录数据 public void readContacts() { Cursor contactCursor = null; try { contactCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); if ( contactCursor != null ) { while (contactCursor.moveToNext()) { //读取通讯录数据 String name = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); String phoneNumber = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); contactList.add(name + "\n" + phoneNumber); } adapter.notifyDataSetChanged(); //刷新ListView } }catch ( SecurityException e) { e.printStackTrace(); } } //权限选择结果回调 @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case 1: { if ( grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED ) { readContacts(); } else { Toast.makeText(this, "你不能读取用户通讯录", Toast.LENGTH_SHORT).show(); } } break; default: break; } }
ok