ContentProvider UriMatcher

40 阅读2分钟

在Android的ContentProvider中,UriMatcher类被用来帮助ContentProvider识别传入的URI,以便知道应该对哪些数据执行操作(如增、删、改、查)。每个UriMatcher对象都维护了一个从URI模式(patterns)到整数值(通常是用户定义的常量)的映射。当ContentProvider接收到一个URI时,它会使用UriMatcher来查找与该URI相匹配的模式,并返回对应的整数值,这个整数值随后可以用来在ContentProvider的代码中区分不同的数据集合或操作。

如何使用UriMatcher

  1. 创建UriMatcher实例: 首先,你需要创建一个UriMatcher的实例。

    private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    
  2. 添加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);
    }
    

    在这个例子中,USERUSER_ID是定义在类中的常量,分别用于区分两个不同的URI模式。"user"模式用于匹配所有用户,而"user/#"模式(其中#是通配符,代表任何数字)用于匹配特定ID的用户。

  3. 在ContentProvider中使用UriMatcher: 在ContentProviderquery()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的方法中自行实现。