Android之URI

来源:互联网 发布:久石让 知乎 编辑:程序博客网 时间:2024/05/01 14:49

一、URI简介

URI包含如下几个部分:

content://usrname:password@com.google.com:80/person/10

1、红色部分:访问资源的命名机制

2、绿色部分:存放资源的主机名,或称为authority

3、蓝色部分:资源本省的名称,由路径表示


二、URI类

android的URI类提供了几个使用接口来处理一个URI路径

1、public static final Uri EMPTY

一个空的URI对象,相等于""

2、public abstract String getAuthority ()

获取URI的authority部分,即usrname:password@com.google.com:80

3、public abstract String getHost ()

获取URI的主机部分,即com.google.com

4、public abstract int getPort ()

获取URI的端口,即80

5、、public abstract String getScheme ()

获取URI的scheme,即content://

6、public abstract String getUserInfo ()

获取URI的用户信息,即usrname:password


三、UriMatcher类

android为URI提供了一个UriMatcher类,用来对URI进行各种匹配。其主要接口如下:

voidaddURI(String authority, String path, int code)
向该UriMatcher中添加一条匹配规则.authority如前所述;path为资源的路径,其中"*"可表示匹配任何字符,"#"表示匹配一个数字;code为当某一URI匹配该规则时,返回的匹配码
int match(Uri uri)
开始匹配一个URI,成功则返回前面设定的code,否则返回UriMatcher.NO_MATCH常量。

以下摘自android:


private static final int PEOPLE = 1;
private static final int PEOPLE_ID = 2;
private static final int PEOPLE_PHONES = 3;
private static final int PEOPLE_PHONES_ID = 4;
private static final int PEOPLE_CONTACTMETHODS = 7;
private static final int PEOPLE_CONTACTMETHODS_ID = 8;


private static final int DELETED_PEOPLE = 20;


private static final int PHONES = 9;
private static final int PHONES_ID = 10;
private static final int PHONES_FILTER = 14;


private static final int CONTACTMETHODS = 18;
private static final int CONTACTMETHODS_ID = 19;


private static final int CALLS = 11;
private static final int CALLS_ID = 12;
private static final int CALLS_FILTER = 15;


private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);


static
{
sURIMatcher.addURI("contacts", "people", PEOPLE);
sURIMatcher.addURI("contacts", "people/#", PEOPLE_ID);
sURIMatcher.addURI("contacts", "people/#/phones", PEOPLE_PHONES);
sURIMatcher.addURI("contacts", "people/#/phones/#", PEOPLE_PHONES_ID);
sURIMatcher.addURI("contacts", "people/#/contact_methods", PEOPLE_CONTACTMETHODS);
sURIMatcher.addURI("contacts", "people/#/contact_methods/#", PEOPLE_CONTACTMETHODS_ID);
sURIMatcher.addURI("contacts", "deleted_people", DELETED_PEOPLE);
sURIMatcher.addURI("contacts", "phones", PHONES);
sURIMatcher.addURI("contacts", "phones/filter/*", PHONES_FILTER);
sURIMatcher.addURI("contacts", "phones/#", PHONES_ID);
sURIMatcher.addURI("contacts", "contact_methods", CONTACTMETHODS);
sURIMatcher.addURI("contacts", "contact_methods/#", CONTACTMETHODS_ID);
sURIMatcher.addURI("call_log", "calls", CALLS);
sURIMatcher.addURI("call_log", "calls/filter/*", CALLS_FILTER);
sURIMatcher.addURI("call_log", "calls/#", CALLS_ID);
}


四、ContentUris类
ContentUris类是android提供的又一个URI的工具类,其作用主要是操作使用"content://"的URI路径后面的ID部分。其主要接口如下:
1、static Uri.BuilderappendId(Uri.Builder builder, long id)
将一个id添加到URI的后面.
2、static long parseId(Uri contentUri)
获取URI后面的路径id.
3、static Uri withAppendedId(Uri contentUri, long id)
类似于appendId,同样是将id添加到URI的后面.

原创粉丝点击