今天看到Uri的匹配器用于匹配Uri,addURI()方法的源码如下:
public void addURI(String authority, String path, int code){ if (code < 0) { throw new IllegalArgumentException("code " + code + " is invalid: it must be positive"); } //以"/"分隔path String[] tokens = path != null ? PATH_SPLIT_PATTERN.split(path) : null; //判断分隔后的数组长度.并取其值 int numTokens = tokens != null ? tokens.length : 0; //当前对象 UriMatcher node = this; for (int i = -1; i < numTokens; i++) { //当前循环变量小于0就取authority,否则就获取分隔后的数组的字符,并赋值给token String token = i < 0 ? authority : tokens[i]; //把当前对象的集合赋值给children ArrayList<UriMatcher> children = node.mChildren; //获取其长度 int numChildren = children.size(); UriMatcher child; int j; for (j = 0; j < numChildren; j++) { //获取children对象的孩子 child = children.get(j); //判断当前的token和child对象中的mText是否相等 if (token.equals(child.mText)) { //把child 赋值给 node; node = child; break; } } //获取循环变量j并判断是否等于children对应的大小.也就是判断是否是最后一个 if (j == numChildren) { // Child not found, create it //没有发现孩子,并创建 child = new UriMatcher(); ///判断当前的token是否等于"#" if (token.equals("#")) { //mWhich=1 child.mWhich = NUMBER; } else if (token.equals("*")) { //mWhich=2 child.mWhich = TEXT; } else { //mWhich=0 child.mWhich = EXACT; } //mText=当前的token child.mText = token; //添加到mChildren集合中 node.mChildren.add(child); //node = child; node = child; } } //node.mCode = code; node.mCode = code; } static final Pattern PATH_SPLIT_PATTERN = Pattern.compile("/");