首页 技术 正文
技术 2022年11月18日
0 收藏 688 点赞 2,243 浏览 1492 个字

(下面内容是阅读郭霖大神的《第一行代码》总结的)

1 概述

内容提供器是Android实现跨程序共享数据的标准方式。

内容提供器的的使用方法有两种,

一是使用已有的内容提供器对其他程序的数据进行访问;二是创建自己的内容提供器,将数据共享给其他程序。

2 使用已有的内容提供器

对于想访问内容提供器中共享数据的程序而言,ContentResolver类包含了它们想要进行的一切操作。

2.1 ContentResolver类简介

下面是Android API中对ContentResolver类的描述。

Android之 内容提供器(1)——使用内容提供器访问其它程序共享的数据

要获取ContentResolver类的实例,我们可以使用context中的getContentResolver().

Android之 内容提供器(1)——使用内容提供器访问其它程序共享的数据

和数据库操作一样,ContentResolver类也提供了对应增删改查的方法。

2.2 Uri

在介绍这些方法前我们需要了解内容URI。内容URI给内容提供器中的数据建立唯一标识(这部分取自郭大神的《第一行代码》)。

它主要有两部分组成,权限(authority)和路径(path)。

权限是用于对不同的应用程序做区分的,一般为了避免冲突,都会采用程序包名的方式来进行命名。

比如某个程序的包名是com.example.app,那么该程序对应的权限就可以命名为com.example.app. provider。

路径则是用于对同一应用程序中不同的表做区分的,通常都会添加到权限的后面。

比如某个程序的数据库里存在两张表,table1和table2,这时就可以将路径分别命名为/table1和/table2。

然后把权限和路径进行组合,内容URI就变成了com.example.app.provider/table1和com.example.app.provider/table2。

不过,目前还很难辨认出这两个字符串就是两个内容URI,我们还需要在字符串的头部加上协议声明。因此,内容URI最标准的格式写法如下:

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

得到内容URI,还需要将它解析成Uri的形式,才能作为参数,传入ContentResolve类中对应的增删改查的方法。

解析URI的方法非常简单

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

2.3 ContentResolver类中的增删改查

增:

Android之 内容提供器(1)——使用内容提供器访问其它程序共享的数据

ContentValues values = new ContentValues();
values.put("name","张三");
values.put("age",27);
getContentResolver().insert(uri, values);

删:

Android之 内容提供器(1)——使用内容提供器访问其它程序共享的数据

getContentResolver().delete(uri, "name = ?", new String[] { "张三" });

改:

Android之 内容提供器(1)——使用内容提供器访问其它程序共享的数据

ContentValues values = new ContentValues();
values.put("name","李四");
values.put("age",29);
getContentResolver().update(uri,values,"name = ? and age = ?",
new String[] = {"张三","28"});

查:

Android之 内容提供器(1)——使用内容提供器访问其它程序共享的数据

Cursor cursor = getContentResolver().query(uri,null, null, null, null);

掌握上面的几个方法,我们就可以使用内容提供器对其他程序共享的数据进行操作了。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,912
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,437
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,252
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,063
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,694
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,732