ContentProvider 内容提供者

内容提供者是android应用程序的主要模块,向应用程序提供内容。通过ContentResolver接口的实现对象来压缩以及提供数据给应用程序。只有在进行应用程序间数据分享时才需要使用内容提供者,否则可以直接使用SQLiteDatabase。ContentProvider是单例模式的,多个程序对其进行操作时,会由同一个ContentProvider进行处理,保证了数据的一致性。

当ContentResolver发出请求时,系统会检查所给的URI的权限并提交给已注册的ContentProvider。ContentProvider总会解析升序部分的URI。而UriMatcher是解析URI的类。

被实现的主要方法有

  • onCreate() :初始化内容提供者,当其他应用通过ContentResolver第一次访问ContentProvider时,该方法会被回调
  • query(Uri, String[], String, String[], String) :向调用者返回数据
  • insert(Uri, ContentValues) :向内容提供者中插入新数据
  • update(Uri, ContentValues, String, String[]) :更新内容提供者中现有的数据
  • delete(Uri, String, String[]) 从内容提供者中删除数据
  • getType(Uri) 返回在内容提供者中的MIME类型数据

操作数据的方法(比如insert和update)可能从任何线程中被调用,其他方法(比如onCreate)只能从应用的主线程中调用。并且需要避免耗时操作。

public ContentProvider()
创建一个ContentProvider实例,必须在清单文件中声明,可以被ContentResolver访问,并且被系统自动创建,因此应用程序一般不直接创建ContentProvider对象。
在创建时,别的对象,大多数方法和变量是没被创建的,子类应该在onCreate()方法中创建自身,而不是通过构造方法。
在应用程序加载完后的主线程中ContentProvider被创建,构造方法不能执行耗时操作,否则应用程序的开启会被延迟。

自定义ContentProvider
1.编写一个ContentProvider的子类
2.实现ContentProvider中的抽象方法。public Bundle call (String method, String arg, Bundle extras)
3.定义ContentProvider的Uri(统一资源标识符)
4.使用UriMatcher对象映射Uri返回代码
5.在AndroidMainfest.xml清单文件中使用标签注册内容提供者。

其他应用程序通过自己的ContentResolver对象调用我们在ContentProvider中重写的方法进行对内容的操作。

private static UriMatcher matcher = null;
        static {
         // 定义一个Uri匹配器。将UriMatcher.NO_MATCH,即-1作为参数。
         matcher = new UriMatcher(UriMatcher.NO_MATCH);
         // 定义一组匹配规则
         // 常量UriMatcher.NO_MATCH表示不匹配任何路径的返回码
         matcher.addURI(AUTHORITY, "words", 1);
         matcher.addURI(AUTHORITY, "newwords", 2);
 }

UriMatcher的方法
addURI(String authority,String path,int code)//往UriMatcher对象中注册Uri

匹配成功后会返回对应的code值

int match(Uri uri) // 匹配uri的方法。找不到匹配的标识符时,该方法返回-1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值