四大组件--ContentProvider

来源:互联网 发布:电子数据交换的意思 编辑:程序博客网 时间:2024/06/18 09:34

简介:

ContentProvider实现访问其他APP的资源(系统资源),其中ContentProvider提供数据,ContentResolver接收并操作数据。当应用使用ContentProvider暴露自己的数据时,不管该应用是否启动,其他APP都可通过Uri访问其数据(增删改查)。
通常ContentProvider为单例模式。

Uri类简介:类似于网站的URL,由头部(content://)、路径path(在manifest清单中的< provider>中的authorities属性中定义)/ 资源部分。如:content://org.providers.xxproviders/word/xxx ,其中word为自定义的工具类,规定能识别的标识码。

Uri uri = Uri.parse("content://org.providers.xxproviders/word/xxx");

编写 ContentProvider:

ContentProvider所要重写的方法:参数较多,但并不是都用得上

  • public boolean onCreate()

  • public Uri insert(Uri uri, ContentValues values):根据uri插入values所对应的数据。

  • public int delete(Uri uri, String selection, String[] selectionArgs):根据uri删除selection所匹配的全部数据。

  • public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs):修改selection所对应的数据为values所对应的数据。

  • public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder):查询selection所匹配的数据,筛选出projection包含的列名,并返回查询得到的Cursor 对象。关于Cursor:http://www.cnblogs.com/TerryBlog/archive/2010/07/05/1771459.html

  • public String getType(Uri uri):返回ContentProvider所提供的数据的MIME类型。

当其他APP调用其ContentResolver实例所对应的insert,delete,update和query方法,ContentResolver会通过Uri访问对应的ContentProvider中的insert,delete,update和query方法。

ContentResolver mContentResolver = Context.getContentResolver();//获取实例

所以说,ContentProvider中重写的方法并不是给自身用的,而是给访问该应用的ContentResolver实例使用的。
manifest中< provider>的exported属性必须为true


Uri工具类:

UriMatcher :
- void addURI( String authority, String Path, int code): 用于向UriMatcher 对象注册Uri(类似于初始化)
- int match(Uri uri):返回Uri 的标识码(code),如果没找到则返回-1,该方法多由于ContentProvider处理ContentResolver传过来的参数的时候。

ContentUris:
- Uri withAppendedId(Uri uri, int id): 为URI添加id
- long parseId(Uri uri): 与match(uri)类似,解析Uri 的标识码。


系统的 ContentProvider:

使用ContentResolver通过系统的Uri,访问系统所提供的资源(如联系人信息,多媒体信息等)。具体功能请参考对应的文档。

原创粉丝点击