跨程序共享数据

能够利用getContentResolver()获取ContentResolver. ContentResolver中提供了一系列方法用于对数据进行CRUD操做.
java

ContentProvider

经过getContentResolver()获取ContentResolver的实例,ContentResolver中提供了一系列方法用于对数据进行CRUD操做.
其中
1.insert() 用于添加
2.update() 用于更新
3.delete() 用于删除
4.query() 用于查询android

内容URI及用法

ContentResolver中的CRUD操做是不接受表名参数的,而是使用一个Uri参数代替。该参数被称为内容URI,由两部分组成:authority和path。
内容URI标准写法:数据库

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

须要将内容URI解析成Uri对象才能够做为参数传入安全

Uri uri=Uri.parse("content://com.example.app.provider/table1");

查询操做

Cursor cursor=getContentResolver().query(uri,projection,selection,selectionArgs,orderBy);

其它操做与之相似,也和SQLite中的操做相像。
markdown

自定义ContentProvider

能够extends ContentProvider,须要覆盖父类的6个方法.app

1.public boolean onCreate():初始化ContentProvider时调用,完成对数据库的建立和升级,返回true则表示ContentProvider初始化成功,返回false表示失败。注意:只有存在ContentResolver尝试访问该程序中的而数据时,ContentProvider才会初始化
2.public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder):从ContentProvider中查询数据。使用uri参数来肯定查询哪一张表,projection用于肯定查询哪些列,selectionselectionArgs用来约束查询内容,sordOreder参数用于对结果进行排序,查询结果放在Cursor中返回。
3.public Uri insert(Uri uri, ContentValues values):向ContentProvider中添加一条数据。
4.public int delete(Uri uri, String selection, String[] selectionArgs):从ContentProvider中删除数据。
5.public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs):更新数据
6.public String getType(Uri uri):根据传入的内容URI来返回相对应的MIME类型。ide

一个内容URI对应的MIME字符串由三部分组成:
1.必须以vnd开头。
2.若是内容URI以路径结尾,则后街androi.cursor.dir/,若是内容URI以id结尾,则后接android.cursor.item/
3.最后街上vnd.<authority>.<path>spa

安全性保证

由于全部的CRUD操做都必定要匹配到相应的内容URI格式才能进行,因此咱们能够控制外部程序可以得到的存储内容。code

相关文章
相关标签/搜索