Chapter 7 跨程序共享数据 内容提供器
虽然 文件和SharedPreferences 存储 提供 MODE_WORLD_READABLE\MODE_WORLD_WRITEABLE 这两种操作模式 ,用于供给其他应用程序可访问当前应用数据 , 但该方式 已被Android4.2版本中废弃了 不推荐使用
ContentProvider 内容提供者
主应用于不同应用程序间实现数据的共享 同时保证被访数据的安全性
分两种
一种是 使用现有的内容提供器来读取和操作相应程序中的数据
一种是 创建自己的内容提供器给自己程序的数据提供外部访问的接口
Android 系统中 自带的电话博 短信 媒体库 等程序的数据 可以借助ContentResolver来访问
Context 的 getContentResolver 得到 contentResolver的实例
ContentResolver 提供 一系列方法 对数据进行 CRUD 操作 insert update delete query
ContentResolver 接受 URI 这个唯一标识符 主要由两部分组成 : 权限 和 路径
权限是用于对不同应用程序作区分的 ,一般为避免冲突 ,选用程序包名来进行命名 比如com.example.app对应的权限可命名为 com.example.app.provider
路径是用于对同一应用程序的不同表作区分,通常添加在权限后面 。比如某程序中存在两张表 table1 和 table2 ,这时路径分别可命名成/table1和table2 ,和权限组合后就是 com.example.app.provider/table1
还需在头部加上协议声明
content://com.example.app.provider/table1
content://com.exmple.app.provider/table2
对内容URI字符串 解析成 URI对象 才可以作为参数传入
Uri uri = Uri.parse("content://com.example.app.provider/table1");
Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
projection 指定查询的列名
selection 指定where的约束条件
selectionArgs 为where中的占位符提供具体的值
sortOrder 指定查询结果的排序方式
private void getContacts() {
Cursor cursor = null;
try {
cursor = getActivity().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));
list.add(displayName+"\n"+number);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
cursor.close();
}
adapter.notifyDataSetChanged();
}
<uses-permission android:name="android.permission.READ_CONTACTS"/>
创建自己的内容提供器