Android学习--11-内容提供器

不一样于文件和SharedPreferences存储中的两种全局读写操做,内容提供器能够选择只对哪一部分数据进行共享,防止数据不会泄露。java

ContentResolver类android

读取手机联系人

List<String> contactsList = new ArrayList<String>();
private void readContacts() {
Cursor cursor = null;
try {
// 查询联系人数据
cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, null, null, null);
while (cursor.moveToNext()) {
// 获取联系人姓名
String displayName = cursor.getString(cursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
// 获取联系人手机号
String number = cursor.getString(cursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
contactsList.add(displayName + "\n" + number);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}

使用了query()方法,传入uri参数。而后对Cursor对象进行遍历,最后关闭。app

固然还须要相应的权限ide

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

自定义内容提供器

就像写个接口同样,提供相应路径,访问我,就给你相应的数据。code

extends ContentProvider

标准的URI写法:xml

content://com.example.app.provider/table1对象

*:表示匹配任意长度的任意字符 #:表示匹配任意长度的数字接口

content://com.example.app.provider/*字符串

那么谁来实现匹配内容URI呢: UriMatcherget

提供了一个addURI() 方法,接收三个参数: 权限、路径、自定义的代码

UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI("com.example.app.provider", "table1", 0);

获取 Uri 对象所对应的 MIME 类型,一个内容 URI 所对应的 MIME字符串主要由三部分组分

  1. 必须以 vnd 开头。
  2. 若是内容 URI 以路径结尾,则后接 android.cursor.dir/,若是内容 URI 以 id 结尾, 则后接 android.cursor.item/。
  3. 最后接上 vnd.<authority>.<path>。
vnd.android.cursor.dir/vnd.com.example.app.provider.table1

内容提供器在 AndroidManifest.xml 文件中注册

<provider
android:name="自定义内容提供器的全名"
android:authorities="包名.provider" >
</provider>

如何去访问自定义的内容提供器呢?

Uri uri = Uri.parse("content://com.example.app.provider/table1");
//查所有 ,到这一步就很熟悉了,遍历取出数据。
Cursor cursor = getContentResolver().query(uri, null, null,null, null);
相关文章
相关标签/搜索