您可能会使用以下内容:
static public Uri getUriWithoutLastNPathParts(final Uri uri, final int n) {
final List<String> segments = uri.getPathSegments();
final String[] newSegments = new String[segments.size() - n];
final Uri.Builder builder = new Uri.Builder();
builder.encodedAuthority(uri.getAuthority());
builder.encodedPath(uri.getPath());
builder.encodedQuery(uri.getQuery());
// no "appendPath", it messes up the thing
for (int i = 0; i < newSegments.length; i++) {
newSegments[i] = segments.get(i);
}
builder.encodedPath(TextUtils.join("/", newSegments));
return builder.build();
}
用法:
Uri uri = Uri.parse("org.mycontentproviderAuthority/path1/path2/3");
Log.i("Segments", uri + " " + getUriWithoutLastNPathParts(uri, 1));
uri = Uri.parse("org.mycontentproviderAuthority/path1/path2/3?foo=bar");
Log.i("Segments", uri + " " + getUriWithoutLastNPathParts(uri, 2));