Android从内容提供者中获取联系人

第一步 申请配置权限


第二步 在布局文件中添加ListView用来显示获取到的联系人

   

第三步 初始化ListView

  private void initView() {
        mLvContacts = findViewById(R.id.lv_contacts);
        mAdapter = new ArrayAdapter(this,android.R.layout.simple_expandable_list_item_1,mContacts);
        mLvContacts.setAdapter(mAdapter);
    }

第四步 动态申请权限

4.1 检查是否有权限

   private boolean checkPermission() {
        return ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED;
    }

4.2 如果有权限,则获取联系人并更新界面

   private void contactsFromContentProvider() {
        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 phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            mContacts.add(name+"\n"+phoneNumber);
        }
        mAdapter.notifyDataSetChanged();
        cursor.close();
    }

4.3 如果没有权限,则动态申请权限

   private void requestPermission() {
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},REQUEST_READ_CONTACTS_PERMISSION_CODE);
    }

4.4 申请权限回调逻辑

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == REQUEST_READ_CONTACTS_PERMISSION_CODE){
            if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                contactsFromContentProvider();
            }else{
                Toast.makeText(this,"您没有读取联系人权限!",Toast.LENGTH_SHORT).show();
            }
        }
    }

你可能感兴趣的:(Android基础)