在Android的ContentProvider
中,UriMatcher
类被用来帮助ContentProvider
识别传入的URI,以便知道应该对哪些数据执行操作(如增、删、改、查)。每个UriMatcher
对象都维护了一个从URI模式(patterns)到整数值(通常是用户定义的常量)的映射。当ContentProvider
接收到一个URI时,它会使用UriMatcher
来查找与该URI相匹配的模式,并返回对应的整数值,这个整数值随后可以用来在ContentProvider
的代码中区分不同的数据集合或操作。
如何使用UriMatcher
-
创建UriMatcher实例: 首先,你需要创建一个
UriMatcher
的实例。private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
-
添加URI模式: 然后,你需要使用
addURI()
方法将你的URI模式添加到UriMatcher
中,并为每个模式指定一个唯一的代码(通常是常量)。static { // 假设有一个URI为 content://com.example.provider.user/user/* sUriMatcher.addURI("com.example.provider.user", "user", USER); // 如果有多个URI模式,可以继续添加 sUriMatcher.addURI("com.example.provider.user", "user/#", USER_ID); }
在这个例子中,
USER
和USER_ID
是定义在类中的常量,分别用于区分两个不同的URI模式。"user"
模式用于匹配所有用户,而"user/#"
模式(其中#
是通配符,代表任何数字)用于匹配特定ID的用户。 -
在ContentProvider中使用UriMatcher: 在
ContentProvider
的query()
、insert()
、update()
、delete()
等方法中,你可以使用UriMatcher
来识别传入的URI,并据此执行相应的操作。@Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { int match = sUriMatcher.match(uri); switch (match) { case USER: // 处理对所有用户的查询 break; case USER_ID: // 处理对特定ID用户的查询 // 可以从uri中提取出用户ID long userId = ContentUris.parseId(uri); break; default: throw new IllegalArgumentException("Unknown URI: " + uri); } // ... 返回Cursor或null }
提取URI中的ID
对于像"user/#"
这样的URI模式,你可能需要从URI中提取出具体的ID。这可以通过ContentUris.parseId(Uri uri)
方法来实现,它会自动解析出URI中#
所代表的数字。
注意事项
- 确保你的URI模式是唯一的,并且与你的
ContentProvider
中的逻辑相匹配。 - 在
UriMatcher
中添加URI模式时,确保使用了正确的authority
(即你在AndroidManifest.xml
中声明的android:authorities
属性值)。 UriMatcher
只负责匹配URI并返回相应的代码,具体的逻辑处理(如数据库查询)需要你在ContentProvider
的方法中自行实现。