android.content.UriMatcher中的Uri Matcher是什么

如何使用它?
有人可以解释下面三行代码的含义吗?

  uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
  uriMatcher.addURI(PROVIDER_NAME, "cte", uriCode);
  uriMatcher.addURI(PROVIDER_NAME, "cte/*", uriCode);
  int res = uriMatcher.match(uri);

最佳答案

当您编写ContentProvider或其他需要响应许多不同URI的类时,UriMatcher是一个方便的类。在您的示例中,用户可以使用以下网址查询您的提供商:

myprovider://cte

要么
myprovider://cte/somestring

构造UriMatcher时,您需要为每个URI提供单独的代码(不仅仅是示例中的“uriCode”)。我通常将UriMatcher实例设为静态,然后将URI添加到静态构造函数中:
private static final int CTE_ALL = 1;
private static final int CTE_FIND = 2;
private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
    uriMatcher.addURI(PROVIDER_NAME, "cte", CTE_ALL);
    uriMatcher.addURI(PROVIDER_NAME, "cte/*", CTE_FIND);
}

然后在ContentProvider中,您可以在查询方法中执行以下操作:
Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    int res = uriMatcher.match(uri);
    switch (res) {
        case CTE_ALL:
            //TODO create a results Cursor with all the CTE results
            break;
        case CTE_FIND:
            //TODO create a results Cursor with the single CTE requested
            break;
    }
    return results;
}

07-24 09:48