美文网首页
Android四大组件--ContentProvider

Android四大组件--ContentProvider

作者: ___瘦不了 | 来源:发表于2020-05-18 17:49 被阅读0次

转载自:https://www.jianshu.com/p/5e13d1fec9c9

概述

ContentProvider的作用是为不同的应用之间数据共享,提供统一的接口,我们知道安卓系统中应用内部的数据是对外隔离的,要想让其它应用能使用自己的数据(例如通讯录)这个时候就用到了ContentProvider。

ContentProvider通过uri来标识其它应用要访问的数据,通过ContentResolver的增、删、改、查方法实现对共享数据的操作。还可以通过注册ContentObserver来监听数据是否发生了变化来对应的刷新页面。

ContentProvider讲解

ContentProvider是一个抽象类,如果我们需要开发自己的内容提供者我们就需要继承这个类并复写其方法,需要实现的主要方法如下:

public boolean onCreate()

在创建ContentProvider时使用

public Cursor query()

用于查询指定uri的数据返回一个Cursor

public Uri insert()

用于向指定uri的ContentProvider中添加数据

public int delete()

用于删除指定uri的数据

public int update()

用户更新指定uri的数据

public String getType()

用于返回指定的Uri中的数据MIME类型

数据访问的方法insert,delete和update可能被多个线程同时调用,此时必须是线程安全的

uri讲解

其它应用可以通过ContentResolver来访问ContentProvider提供的数据,而ContentResolver通过uri来定位自己要访问的数据,所以我们要先了解uri。URI(Universal Resource Identifier)统一资源定位符,如果您使用过安卓的隐式启动就会发现,在隐式启动的过程中我们也是通过uri来定位我们需要打开的Activity并且可以在uri中传递参数。URI的格式如下:

[scheme:][//host:port][path][?query]

单单看这个可能我们并不知道是什么意思,下面来举个栗子就一目了然了

URI:http://www.baidu.com:8080/wenku/jiatiao.html?id=123456&name=jack

scheme:根据格式我们很容易看出来scheme为http

host:www.baidu.com

port:就是主机名后面path前面的部分为8080

path:在port后面?的前面为wenku/jiatiao.html

query:?之后的都是query部分为 id=123456$name=jack

uri的各个部分在安卓中都是可以通过代码获取的,下面我们就以上面这个uri为例来说下获取各个部分的方法:

getScheme() :获取Uri中的scheme字符串部分,在这里是http

getHost():获取Authority中的Host字符串,即www.baidu.com

getPost():获取Authority中的Port字符串,即 8080

getPath():获取Uri中path部分,即 wenku/jiatiao.html

getQuery():获取Uri中的query部分,即 id=15&name=du

到这里关于uri的部分就讲解完了,下面让我们通过一个自定义ContentProvider实例来说下自定义ContentProvider的流程以及怎么使用ContentResolver操作ContentProvider的数据

声明

  <provider
        android:authorities="com.jrmf360.studentProvider"
        android:name=".StudentContentProvider"
        android:exported="true"/>

这里的authorities唯一标识该内容提供者,这样其它的应用才可以找到该内容提供者并操作它的数据;exported为true当前内容提供者可以被其它应用使用,默认为true。

操作ContentProvider

获取ContentResolver

   contentResolver = getContentResolver();

通过ContentResolver来操作数据

ContentValues contentValues = new ContentValues();
        contentValues.put("name", "新插入");
        contentValues.put("age", "-100");
        contentValues.put("desc", "我是新插入的呦。。。");
        contentResolver.insert(STUDENT_URI, contentValues);

相关文章

网友评论

      本文标题:Android四大组件--ContentProvider

      本文链接:https://www.haomeiwen.com/subject/rirpohtx.html