Uri、UriMatcher、ContentUris详解及3者联系使用

来源:互联网 发布:linux配置bond模式1 编辑:程序博客网 时间:2024/05/16 18:47
 

1.     Uri 

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

 eg.第一部分"content://"

       第二部分"com.hyz"

所有联系人的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.

 

首先第一步,初始化:

UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); 

 

第二步注册需要的Uri:

//PEOPLE和PEOPLE_ID就是匹配成功时的返回码

matcher.addURI("com.hyz", "people", PEOPLE);  

matcher.addURI("com.hyz", "person/#", PEOPLE_ID); 

 

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

Uri  uri = Uri.parse("content://" + "com.hyz" + "/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;  

       } 

 

match方法匹配后会返回一个匹配码Code,即在使用注册方法addURI时传入的第三个参数。

 

常量:UriMatcher.NO_MATCH 表示不匹配任何路径的返回码

  # :匹配任意数字

* :匹配任意文本

 

3.ContentUris

 

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

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

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

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