Android 应用程序之间数据共享—ContentResolver

深度理解嵌入(embedding)层 首先从one_hot开始: one_hot的优点:计算方便快捷、表达能力强。 one_hot的缺点:过于稀疏,过于占用资源,尤其是在数据量特别大时;数据之间完全独立。 阅读详情
 

Android 应用程序之间数据共享—ContentResolver

Android是如何实现应用程序之间数据共享的?一个应用程序可以将自己的数据完全暴露出去,外界更本看不到,也不用看到这个应用程序暴露的数据是如何存储的,或者是使用数据库还是使用文件,还是通过网上获得,这些一切都不重要,重要的是外界可以通过这一套标准及统一的接口和这个程序里的数据打交道,例如:添加(insert)、删除(delete)、查询(query)、修改(update),当然需要一定的权限才可以。

如何将应用程序的数据暴露出去? Android提供了ContentProvider,一个程序可以通过实现一个Content provider的抽象接口将自己的数据完全暴露出去,而且Content providers是以类似数据库中表的方式将数据暴露。Content providers存储和检索数据,通过它可以让所有的应用程序访问到,这也是应用程序之间唯一共享数据的方法。要想使应用程序的数据公开化,可通过2种方法:创建一个属于你自己的Content provider或者将你的数据添加到一个已经存在的Content provider中,前提是有相同数据类型并且有写入Content provider的权限。

如何通过一套标准及统一的接口获取其他应用程序暴露的数据?Android提供了ContentResolver,外界的程序可以通过ContentResolver接口访问ContentProvider提供的数据。

当前篇主要说明,如何获取其它应用程序共享的数据,比如获取Android 手机电话薄中的信息。

什么是URI?

在学习如何获取ContentResolver前,有个名词是必须了解的:URI。URI是网络资源的定义,在Android中赋予其更广阔的含义,先看个例子,如下:
URI
将其分为A,B,C,D 4个部分:
A:标准前缀,用来说明一个Content Provider控制这些数据,无法改变的;
B:URI的标识,它定义了是哪个Content Provider提供这些数据。对于第三方应用程序,为了保证URI标识的唯一性,它必须是一个完整的、小写的   类名。这个标识在<provider> 元素的 authorities属性中说明:
<provider name=”.TransportationProvider”  authorities=”com.example.transportationprovider”  . . .  >
C:路径,Content Provider使用这些路径来确定当前需要生什么类型的数据,URI中可能不包括路径,也可能包括多个;
D:如果URI中包含,表示需要获取的记录的ID;如果没有ID,就表示返回全部;
由于URI通常比较长,而且有时候容易出错,切难以理解。所以,在Android当中定义了一些辅助类,并且定义了一些常量来代替这些长字符串,例如:People.CONTENT_URI

ContentResolver 介绍说明

看完这些介绍,大家一定就明白了,ContentResolver是通过URI来查询ContentProvider中提供的数据。除了URI以外,还必须知道需要获取的数据段的名称,以及此数据段的数据类型。如果你需要获取一个特定的记录,你就必须知道当前记录的ID,也就是URI中D部分。

前面也提到了Content providers是以类似数据库中表的方式将数据暴露出去,那么ContentResolver也将采用类似数据库的操作来从Content providers中获取数据。现在简要介绍ContentResolver的主要接口,如下:

返回值函数声明
final Uriinsert(Uri url, ContentValues values)Inserts a row into a table at the given URL.
final intdelete(Uri url, String where, String[] selectionArgs)Deletes row(s) specified by a content URI.
final Cursorquery(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)Query the given URI, returning a Cursor over the result set.
final intupdate(Uri uri, ContentValues values, String where, String[] selectionArgs)Update row(s) in a content URI.

看到这里,是否感觉与数据库的操作基本一样的?就是这样的,详细解析请参考Android SQLite解析篇中的说明,不在此详细说明。

最后一个问题:如何获取ContentResolver?调用getContentResolver (),例如:ContentResolver cr = getContentResolver();

制作ContentResolver实例

以上就完全介绍了如何获取、使用ContentResolver,启动Eclipes,制作一个完整的实例如下:
ContentResolver
打开showcontent.java,修改如下:

package moandroid.showcontact;

import android.app.ListActivity;

import android.database.Cursor;

import android.os.Bundle;

import android.provider.Contacts.Phones;

import android.widget.ListAdapter;

import android.widget.SimpleCursorAdapter;

public class showcontact extends ListActivity {

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

Cursor c = getContentResolver().query(Phones.CONTENT_URI, null, null, null, null);

startManagingCursor(c);

ListAdapter adapter = new SimpleCursorAdapter(this,

android.R.layout.simple_list_item_2, c,

new String[] { Phones.NAME, Phones.NUMBER },

new int[] { android.R.id.text1, android.R.id.text2 });

setListAdapter(adapter);

}

}

然后在AndroidManifest.XML中<application>元素前增加如下许可:
<uses-permission android:name=”android.permission.READ_CONTACTS” />
最后运行程序,在模拟器启动后,单击Menu返回到Home界面,打开Contacts选择Contacts标签页,添加2个联系人信息。返回到Home,选择moandroid.showcontact运行,刚添加的2个联系人信息将显示在界面上,如下:
Content

总结说明

ContentResolver的使用极大的方便了应用程序之间共享数据,如何将应用程序的数据完全暴露给给他应用程序使用了,将在下篇文章Android 应用程序之间数据共享—-ContentProvider中说明。

 

Ubuntu22.04下安装LDAP 在Ubuntu22.04的时候可以使用apt的方式来安装,在安装LDAP的web 服务器的时候可以考虑选择 LDAP 帐户管理器 (LAM)。因为 PHPLDAPadmin 安装时需要 php 的环境依赖,相对来说安装麻烦。此外在 PHPLDAPadmin 中创建组织和用户时与平常的语法有很大不同,对新手来说不友好。 阅读详情

相关推荐

用友U8库龄分析避坑指南:物料出入库日期计算的5个常见错误

本文深入剖析了在用友U8系统中进行库龄分析时,物料出入库日期计算的五个常见陷阱。从数据源选择、业务类型过滤、计价方式逻辑、期初数据处理到查询性能优化,逐一解析错误根源并提供避坑指南,帮助企业获得准确的库龄数据,有效管理库存与资金风险。

weixin_29209801的博客 457

android_day09

1.为什么需要内容提供者(contentProvider)     [1]如何创建一个数据库  定义一个类继承SqliteOpenHelper     [2]sqlite3打开数据库     [3]chmod linux 下修改文件的权限     [4]使用内容提供者  把私有的数据库内容给暴露出来 2.内容提供者原理          应用2    应用1     应用2不能直接访问应用1私...

a974627751的博客 395

有限元中的对称魔法:用1/6模型算整个涡轮叶片(含MATLAB代码)

本文深入解析了有限元分析中针对循环对称结构的高效求解策略。通过利用涡轮叶片等结构的几何重复性,仅需对1/6基本扇区建模并施加循环对称条件,即可精确推演整体力学行为,大幅降低计算规模。文章从数学原理推导到MATLAB代码实现,提供了完整的实战指南,适用于旋转机械的静力、模态及谐响应分析。

fire9的博客 312

Android 数据库 notify,Android - contentResolver.notifyChange()降低性能(Android - contentResolver.notifyChan...

I have a MyContentProvider class that overrides bulkInsert(). Within this method, I use a SQLite transaction to insert about 4,000 rows into the database, which takes about 25 seconds on a Samsung Gal...

weixin_32418703的博客 744

STM32F407 UART4串口DMA收发实战:告别频繁中断,用空闲中断+DMA搞定不定长数据

本文详细介绍了STM32F407 UART4串口结合DMA和空闲中断实现高效不定长数据收发的实战方案。通过DMA硬件级数据搬运和空闲中断智能帧检测,显著降低CPU占用率,提升通信效率,适用于工业传感器数据采集和智能设备通信场景。

weixin_42631411的博客 158

【驱动适配】高通sa522平台tac5x1x驱动适配全指南

本手册详细介绍了TAC5301-Q1音频编解码器在高通sa525平台Linux系统下的驱动适配流程。主要内容包括:1)TAC5301-Q1核心特性(车载级音频Codec、关键接口和功能);2)驱动适配依赖(高通声卡驱动、ALSA SoC框架等);3)I2S协议原理及主从模式说明;4)硬件准备与检查要点;5)完整的驱动移植步骤(代码移植、Kconfig/Makefile修改、设备树配置)。该手册适用于嵌入式音频开发工程师快速完成TAC5301-Q1芯片的驱动移植与验证工作。

嵌入式博哥的博客 305

内容监听者

ContentProvider的数据一旦发生改变,程序就会调用如下代码: getContext().getContentResolver().notifyChange(uri, null); 该代码通知所有监听在该Uri上的监听者,ContentProvider的数据发生了变化。 后面的例子,sms的ContentProvider发生变化,"content://sms"就为flag。 所以

cool_oyty的专栏 909

Cadence Sigrity PowerSI实战:从.brd到S参数提取的完整避坑指南

本文详细介绍了使用Cadence Sigrity PowerSI进行信号完整性分析的完整流程,从.brd文件预处理到S参数提取的关键技巧。通过实战案例和避坑指南,帮助工程师高效解决高速PCB设计中的信号质量问题,提升仿真精度和设计效率。

carrot的博客 696

content provider的使用!

在Android系统上,每一个应用程序都有一个独立的用户ID。为什么要给每一个应用程序分配一个独立的用户ID呢?这是为了保护各个应用程序的数据不被其它应用程序恶意破坏而设计的。例如,只有当一个用户对某个文件拥有读权限时,这个用户才可以调用read系统调用来读取这个文件的内容。Android系统继承了Linux系统管理文件的方法,为每一个应用程序分配一个独立的用户ID和用户组ID,而由这个应用程序创

joby1981的专栏 1699

COMSOL+AI实战:5个超实用技巧让你的仿真效率翻倍(附Python代码)

本文详细介绍了如何将人工智能(AI)与COMSOL仿真软件结合,通过Python脚本实现五大实用技巧,包括自动化生成数据集、构建代理模型、集成AI优化算法、利用神经网络加速场量求解以及智能结果分析,从而显著提升多物理场仿真的效率和自动化水平。

weixin_29230865的博客 444

【camera-radar】基于ROS的多传感器融合感知系统实现(雷达+相机)(2)

实现功能:代码下载地址:下载地址 1)基于深度学习的目标检测;2)基于雷达的距离估计和预测;3)多传感器感知结果融合模块。 相机感知模块解析 4. Run nodes: python3 fusion_node/main.py python3 gps_node/main.py python3 radar_node/main.py python3 2d_detection_node/main.py #(additional instructions in 2d_detection_node/README.m

踟蹰横渡口,彳亍上滩舟。 9952

在Android 应用程序之间数据共享—-ContentResolver

在Android 应用程序之间数据共享—-ContentResolver中,已经说明了Android是如何实现应用程序之间数据共享的,并详细解析了如何获取其他应用程序共享的数据。ContentProviders存储和检索数据,通过它可以让所有的应用程序访问到,这也是应用程序之间唯一共享数据的方法。那么如何将应用程序的数据暴露出去?通过以前文章的学习,知道ContentResolver是通过Cont

xiaoj13的专栏 1051

Vue - 详细实现低代码平台,支持拖曳式可视化生成应用软件功能,用户通过拖拽元素、搭积木的方式创建应用(适合迭代的基础架构、低代码平台)

Vue低代码平台-拖曳式拖拉拽可视化生成应用软件,拖拽式低代码数据可视化开发平台,vue实现拖拽,拖拽式Vue组件代码生成平台,基于vue的可视化拖拽代码生成工具,Vue实现可拖拽组件的方法,一个低代码平台的前端部分,靠拖拉拽生成页面。Vue技术栈从零实现低代码可视化搭建平台示例,低代码轮子,通过拖拽就可生成Vue代码的平台来了,vue低代码平台开发相关比低代码更强大的零代码开发平台,这款低代码SAAS数据可视化工具,拖拽生成大屏。vue实现拖拽效果,Vue自由拖拽缩放组件,自定义组件(文本、图片

🏆 前端领域优质创作者 1万+

【转】Android 应用程序之间数据共享—ContentResolver

Android是如何实现应用程序之间数据共享的?一个应用程序可以将自己的数据完全暴露出去,外界更本看不到,也不用看到这个应用程序暴露的数据是如何存储的,或者是使用数据库还是使用文件,还是通过网上获得,这些一切都不重要,重要的是外界可以通过这一套标准及统一的接口和这个程序里的数据打交道,例如:添加(insert)、删除(delete)、查询(query)、修改(update),当然需要...

andy76123的博客 108

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

RK3588 BSP调试实战:RTC实时时钟从硬件到驱动的全链路避坑指南

实时时钟(RTC)是嵌入式系统中维持掉电走时与定时唤醒的基础模块,其精度与可靠性直接影响设备的时间戳准确性和低功耗唤醒能力。RTC的工作原理依赖32.768kHz晶振分频与独立供电域切换,在Linux内核中通过设备树匹配驱动并借助hwclock、rtcwake等工具完成用户态交互。在RK3588等高性能处理器平台上,RTC调试涉及PMIC供电、晶振负载电容计算、I2C总线通信及唤醒源配置等多个技术环节,是BSP开发中典型的跨软硬件调试场景。工业边缘计算、车载终端与物联网网关等应用对掉电走时和定时唤醒有明确需

weixin_34389926的博客 229

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

Android 应用程序之间数据共享—ContentResolver与ContentProvider

Android是如何实现应用程序之间数据共享的?一个应用程序可以将自己的数据完全暴露出去,外界更本看不到,也不用看到这个应用程序暴露的数据是如何存储的,或者是使用数据库还是使用文件,还是通过网上获得,这些一切都不重要,重要的是外界可以通过这一套标准及统一的接口和这个程序里的数据打交道,例如:添加(insert)、删除(delete)、查询(query)、修改(update),当然需要一定的权限才...

foozhe2000的专栏 346

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: JSP中实现网站自动登录
下一篇: android基础——Handler
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值