Android Uri、UriMatcher、ContentUris详解

来源:互联网 发布:ipad4软件更新打不开 编辑:程序博客网 时间:2024/05/02 00:38

1.Uri

通用资源标志符(Universal Resource Identifier, 简称"URI")。

Uri代表要操作的数据,Android上可用的每种资源 - 图像、视频片段等都可以用Uri来表示。

 

URI一般由三部分组成:

访问资源的命名机制。

存放资源的主机名。

资源自身的名称,由路径表示。

 

Android的Uri由以下三部分组成: "content://"、数据的路径、标示ID(可选)

举些例子,如:

所有联系人的Uri: content://contacts/people

某个联系人的Uri: content://contacts/people/5

所有图片Uri: content://media/external

某个图片的Uri:content://media/external/images/media/4

 

我们很经常需要解析Uri,并从Uri中获取数据。

Android系统提供了两个用于操作Uri的工具类,分别为UriMatcher 和ContentUris 。

虽然这两类不是非常重要,但是掌握它们的使用,会便于我们的开发工作。

下面就一起看一下这两个类的作用。

 

2.UriMatcher

UriMatcher 类主要用于匹配Uri.

a)       Public void addURI(String authority,String path,int code)

添加一个用于匹配的URI,当匹配成功时则code。URI可以是精确的字符串,uri中带有*表示可匹配任意text,#表示只能匹配数字。

Authority:用于匹配的域名;

Path:匹配路径,*表示text的占位符,#表示使用数字的占位符;

Code:当使用匹配成功后返回code,值需要大于0,否则抛出IllegalArgument异常。

此方法将authority按照”/”进行拆分,然后将拆分后的每一部分保存到UriMatcher类型的ArrayList中;在添加的时候会判断当前authority是否已经添加过,若已加则break;若未添加过,则判断是否含有”#”则将其标识成1代表域名后面跟随的是数字;”*”标识成2,代表域名后面跟随的是文本;0代表后面没有跟随数据;最后创建一个新的UriMatcher对象添加到集合中。

b)       Public int match(Uri uri)

尝试在url中匹配相对应的路径

Uri:指定需要匹配的url;

返回值:在使用addURI时产生的code,若没有匹配则返回-1。

使用uri. getPathSegments()获取uri中各段存入list中,若list size为0或uri的Authority为null则返回默认值(此默认值在new时指定,若为指定则为-1);

然后遍历ArrayLis<UriMatcher>进行匹配uri。

使用方法如下。

首先第一步,初始化:

UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);

 

第二步注册需要的Uri

matcher.addURI("com.yfz.Lesson", "people", PEOPLE);  matcher.addURI("com.yfz.Lesson", "person/#", PEOPLE_ID);

第三部,与已经注册的Uri进行匹配:

Uri uri = Uri.parse("content://" + "com.yfz.Lesson" + "/people");   int match = matcher.match(uri);          switch (match)          {              case PEOPLE:                  return "vnd.android.cursor.dir/people";              case PEOPLE_ID:                  return "vnd.android.cursor.item/people";              default:                  return null;          }   


 

3.ContentUris

ContentUris 类用于获取Uri路径后面的ID部分

1)为路径加上ID: withAppendedId(uri, id)

比如有这样一个Uri

Uri uri = Uri.parse("content://com.yfz.Lesson/people")

通过withAppendedId方法,为该Uri加上ID

Uri resultUri = ContentUris.withAppendedId(uri, 10);

最后resultUri为: content://com.yfz.Lesson/people/10

2)从路径中获取ID: parseId(uri)

Uri uri = Uri.parse("content://com.yfz.Lesson/people/10")long personid = ContentUris.parseId(uri); 

最后personid 为 :10

 

 

原文地址:http://blog.csdn.net/feng88724/article/details/6331396 

 

 

 

 

 

 

0 0
原创粉丝点击