Android有四大组件,对于activity和service用的比较多,比较熟悉。对于ContentProvider,由于数据在Android中是私有的,不同应用的信息是不可以直接访问的,为了共享这些信息,所以有了ContentProvider。使用ContentProvider制定需要共享的数据,而其他程序则不知道数据来源、存储方式、存储路径的情况下,对共享数据进行增、删、改、查、操作,即提高了数据的访问效率,又保护了数据。

        下面演示如何通过ContentResolver获取通讯录里面的数据:

        1.新建Contact 的类,设置get和set.

public class Contact {
    private long id;
    private String name;
    private String phone;

    public Contact(long id, String name, String phone) {
        this.id = id;
        this.name = name;
        this.phone = phone;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    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;
    }
}

        2.修改AndroidManifest.xml,增加READ_CONTACTS权限。

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

        3.在mainactivity中,判断是否有权限,如果有权限,执行readContacts();


if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
    != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,
    new String[]{Manifest.permission.READ_CONTACTS}, REQUEST);
}else {
    readContacts();
}

   
private void readContacts() {
    List<Contact> data = new ArrayList<>();
    Cursor cursor1 =                 
          getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);
    if(cursor1 != null){
        while(cursor1.moveToNext()) {
        long id = cursor1.getLong(cursor1.getColumnIndex(ContactsContract.Contacts._ID));
        String name = cursor1.getString(cursor1.getColumnIndex(                 
        ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME_PRIMARY));
        Cursor cursor2 = getContentResolver().query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id,null, null);
                if (cursor2 != null) {
                    while (cursor2.moveToNext()) {
                        String phone = cursor2.getString(cursor2.getColumnIndex(
                                ContactsContract.CommonDataKinds.Phone.NUMBER));
                        data.add(new Contact(id, name, phone));
                    }
                    cursor2.close();
                }
            }
            cursor1.close();
        }
    }

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐