DocumentsContract.java revision b9fbb7290b02de1ce621deaa2d28a5e42f2e0937
1/* 2 * Copyright (C) 2013 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.provider; 18 19import static android.net.TrafficStats.KB_IN_BYTES; 20import static android.system.OsConstants.SEEK_SET; 21 22import android.content.ContentProviderClient; 23import android.content.ContentResolver; 24import android.content.Context; 25import android.content.Intent; 26import android.content.pm.ResolveInfo; 27import android.content.res.AssetFileDescriptor; 28import android.database.Cursor; 29import android.graphics.Bitmap; 30import android.graphics.BitmapFactory; 31import android.graphics.Matrix; 32import android.graphics.Point; 33import android.media.ExifInterface; 34import android.net.Uri; 35import android.os.Bundle; 36import android.os.CancellationSignal; 37import android.os.OperationCanceledException; 38import android.os.ParcelFileDescriptor; 39import android.os.ParcelFileDescriptor.OnCloseListener; 40import android.os.RemoteException; 41import android.system.ErrnoException; 42import android.system.Os; 43import android.util.Log; 44 45import libcore.io.IoUtils; 46 47import java.io.BufferedInputStream; 48import java.io.File; 49import java.io.FileDescriptor; 50import java.io.FileInputStream; 51import java.io.FileNotFoundException; 52import java.io.IOException; 53import java.util.List; 54 55/** 56 * Defines the contract between a documents provider and the platform. 57 * <p> 58 * To create a document provider, extend {@link DocumentsProvider}, which 59 * provides a foundational implementation of this contract. 60 * <p> 61 * All client apps must hold a valid URI permission grant to access documents, 62 * typically issued when a user makes a selection through 63 * {@link Intent#ACTION_OPEN_DOCUMENT}, {@link Intent#ACTION_CREATE_DOCUMENT}, 64 * or {@link Intent#ACTION_OPEN_DOCUMENT_TREE}. 65 * 66 * @see DocumentsProvider 67 */ 68public final class DocumentsContract { 69 private static final String TAG = "Documents"; 70 71 // content://com.example/root/ 72 // content://com.example/root/sdcard/ 73 // content://com.example/root/sdcard/recent/ 74 // content://com.example/root/sdcard/search/?query=pony 75 // content://com.example/document/12/ 76 // content://com.example/document/12/children/ 77 // content://com.example/tree/12/document/24/ 78 // content://com.example/tree/12/document/24/children/ 79 80 private DocumentsContract() { 81 } 82 83 /** 84 * Intent action used to identify {@link DocumentsProvider} instances. This 85 * is used in the {@code <intent-filter>} of a {@code <provider>}. 86 */ 87 public static final String PROVIDER_INTERFACE = "android.content.action.DOCUMENTS_PROVIDER"; 88 89 /** {@hide} */ 90 public static final String EXTRA_PACKAGE_NAME = "android.content.extra.PACKAGE_NAME"; 91 92 /** {@hide} */ 93 public static final String EXTRA_SHOW_ADVANCED = "android.content.extra.SHOW_ADVANCED"; 94 95 /** 96 * Included in {@link AssetFileDescriptor#getExtras()} when returned 97 * thumbnail should be rotated. 98 * 99 * @see MediaStore.Images.ImageColumns#ORIENTATION 100 * @hide 101 */ 102 public static final String EXTRA_ORIENTATION = "android.content.extra.ORIENTATION"; 103 104 /** {@hide} */ 105 public static final String ACTION_MANAGE_ROOT = "android.provider.action.MANAGE_ROOT"; 106 /** {@hide} */ 107 public static final String ACTION_MANAGE_DOCUMENT = "android.provider.action.MANAGE_DOCUMENT"; 108 109 /** 110 * Buffer is large enough to rewind past any EXIF headers. 111 */ 112 private static final int THUMBNAIL_BUFFER_SIZE = (int) (128 * KB_IN_BYTES); 113 114 /** 115 * Constants related to a document, including {@link Cursor} column names 116 * and flags. 117 * <p> 118 * A document can be either an openable stream (with a specific MIME type), 119 * or a directory containing additional documents (with the 120 * {@link #MIME_TYPE_DIR} MIME type). A directory represents the top of a 121 * subtree containing zero or more documents, which can recursively contain 122 * even more documents and directories. 123 * <p> 124 * All columns are <em>read-only</em> to client applications. 125 */ 126 public final static class Document { 127 private Document() { 128 } 129 130 /** 131 * Unique ID of a document. This ID is both provided by and interpreted 132 * by a {@link DocumentsProvider}, and should be treated as an opaque 133 * value by client applications. This column is required. 134 * <p> 135 * Each document must have a unique ID within a provider, but that 136 * single document may be included as a child of multiple directories. 137 * <p> 138 * A provider must always return durable IDs, since they will be used to 139 * issue long-term URI permission grants when an application interacts 140 * with {@link Intent#ACTION_OPEN_DOCUMENT} and 141 * {@link Intent#ACTION_CREATE_DOCUMENT}. 142 * <p> 143 * Type: STRING 144 */ 145 public static final String COLUMN_DOCUMENT_ID = "document_id"; 146 147 /** 148 * Concrete MIME type of a document. For example, "image/png" or 149 * "application/pdf" for openable files. A document can also be a 150 * directory containing additional documents, which is represented with 151 * the {@link #MIME_TYPE_DIR} MIME type. This column is required. 152 * <p> 153 * Type: STRING 154 * 155 * @see #MIME_TYPE_DIR 156 */ 157 public static final String COLUMN_MIME_TYPE = "mime_type"; 158 159 /** 160 * Display name of a document, used as the primary title displayed to a 161 * user. This column is required. 162 * <p> 163 * Type: STRING 164 */ 165 public static final String COLUMN_DISPLAY_NAME = OpenableColumns.DISPLAY_NAME; 166 167 /** 168 * Summary of a document, which may be shown to a user. This column is 169 * optional, and may be {@code null}. 170 * <p> 171 * Type: STRING 172 */ 173 public static final String COLUMN_SUMMARY = "summary"; 174 175 /** 176 * Timestamp when a document was last modified, in milliseconds since 177 * January 1, 1970 00:00:00.0 UTC. This column is required, and may be 178 * {@code null} if unknown. A {@link DocumentsProvider} can update this 179 * field using events from {@link OnCloseListener} or other reliable 180 * {@link ParcelFileDescriptor} transports. 181 * <p> 182 * Type: INTEGER (long) 183 * 184 * @see System#currentTimeMillis() 185 */ 186 public static final String COLUMN_LAST_MODIFIED = "last_modified"; 187 188 /** 189 * Specific icon resource ID for a document. This column is optional, 190 * and may be {@code null} to use a platform-provided default icon based 191 * on {@link #COLUMN_MIME_TYPE}. 192 * <p> 193 * Type: INTEGER (int) 194 */ 195 public static final String COLUMN_ICON = "icon"; 196 197 /** 198 * Flags that apply to a document. This column is required. 199 * <p> 200 * Type: INTEGER (int) 201 * 202 * @see #FLAG_SUPPORTS_WRITE 203 * @see #FLAG_SUPPORTS_DELETE 204 * @see #FLAG_SUPPORTS_THUMBNAIL 205 * @see #FLAG_DIR_PREFERS_GRID 206 * @see #FLAG_DIR_PREFERS_LAST_MODIFIED 207 */ 208 public static final String COLUMN_FLAGS = "flags"; 209 210 /** 211 * Size of a document, in bytes, or {@code null} if unknown. This column 212 * is required. 213 * <p> 214 * Type: INTEGER (long) 215 */ 216 public static final String COLUMN_SIZE = OpenableColumns.SIZE; 217 218 /** 219 * MIME type of a document which is a directory that may contain 220 * additional documents. 221 * 222 * @see #COLUMN_MIME_TYPE 223 */ 224 public static final String MIME_TYPE_DIR = "vnd.android.document/directory"; 225 226 /** 227 * Flag indicating that a document can be represented as a thumbnail. 228 * 229 * @see #COLUMN_FLAGS 230 * @see DocumentsContract#getDocumentThumbnail(ContentResolver, Uri, 231 * Point, CancellationSignal) 232 * @see DocumentsProvider#openDocumentThumbnail(String, Point, 233 * android.os.CancellationSignal) 234 */ 235 public static final int FLAG_SUPPORTS_THUMBNAIL = 1; 236 237 /** 238 * Flag indicating that a document supports writing. 239 * <p> 240 * When a document is opened with {@link Intent#ACTION_OPEN_DOCUMENT}, 241 * the calling application is granted both 242 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and 243 * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}. However, the actual 244 * writability of a document may change over time, for example due to 245 * remote access changes. This flag indicates that a document client can 246 * expect {@link ContentResolver#openOutputStream(Uri)} to succeed. 247 * 248 * @see #COLUMN_FLAGS 249 */ 250 public static final int FLAG_SUPPORTS_WRITE = 1 << 1; 251 252 /** 253 * Flag indicating that a document is deletable. 254 * 255 * @see #COLUMN_FLAGS 256 * @see DocumentsContract#deleteDocument(ContentResolver, Uri) 257 * @see DocumentsProvider#deleteDocument(String) 258 */ 259 public static final int FLAG_SUPPORTS_DELETE = 1 << 2; 260 261 /** 262 * Flag indicating that a document is a directory that supports creation 263 * of new files within it. Only valid when {@link #COLUMN_MIME_TYPE} is 264 * {@link #MIME_TYPE_DIR}. 265 * 266 * @see #COLUMN_FLAGS 267 * @see DocumentsProvider#createDocument(String, String, String) 268 */ 269 public static final int FLAG_DIR_SUPPORTS_CREATE = 1 << 3; 270 271 /** 272 * Flag indicating that a directory prefers its contents be shown in a 273 * larger format grid. Usually suitable when a directory contains mostly 274 * pictures. Only valid when {@link #COLUMN_MIME_TYPE} is 275 * {@link #MIME_TYPE_DIR}. 276 * 277 * @see #COLUMN_FLAGS 278 */ 279 public static final int FLAG_DIR_PREFERS_GRID = 1 << 4; 280 281 /** 282 * Flag indicating that a directory prefers its contents be sorted by 283 * {@link #COLUMN_LAST_MODIFIED}. Only valid when 284 * {@link #COLUMN_MIME_TYPE} is {@link #MIME_TYPE_DIR}. 285 * 286 * @see #COLUMN_FLAGS 287 */ 288 public static final int FLAG_DIR_PREFERS_LAST_MODIFIED = 1 << 5; 289 290 /** 291 * Flag indicating that a document can be renamed. 292 * 293 * @see #COLUMN_FLAGS 294 * @see DocumentsContract#renameDocument(ContentProviderClient, Uri, 295 * String) 296 * @see DocumentsProvider#renameDocument(String, String) 297 */ 298 public static final int FLAG_SUPPORTS_RENAME = 1 << 6; 299 300 /** 301 * Flag indicating that document titles should be hidden when viewing 302 * this directory in a larger format grid. For example, a directory 303 * containing only images may want the image thumbnails to speak for 304 * themselves. Only valid when {@link #COLUMN_MIME_TYPE} is 305 * {@link #MIME_TYPE_DIR}. 306 * 307 * @see #COLUMN_FLAGS 308 * @see #FLAG_DIR_PREFERS_GRID 309 * @hide 310 */ 311 public static final int FLAG_DIR_HIDE_GRID_TITLES = 1 << 16; 312 } 313 314 /** 315 * Constants related to a root of documents, including {@link Cursor} column 316 * names and flags. A root is the start of a tree of documents, such as a 317 * physical storage device, or an account. Each root starts at the directory 318 * referenced by {@link Root#COLUMN_DOCUMENT_ID}, which can recursively 319 * contain both documents and directories. 320 * <p> 321 * All columns are <em>read-only</em> to client applications. 322 */ 323 public final static class Root { 324 private Root() { 325 } 326 327 /** 328 * Unique ID of a root. This ID is both provided by and interpreted by a 329 * {@link DocumentsProvider}, and should be treated as an opaque value 330 * by client applications. This column is required. 331 * <p> 332 * Type: STRING 333 */ 334 public static final String COLUMN_ROOT_ID = "root_id"; 335 336 /** 337 * Flags that apply to a root. This column is required. 338 * <p> 339 * Type: INTEGER (int) 340 * 341 * @see #FLAG_LOCAL_ONLY 342 * @see #FLAG_SUPPORTS_CREATE 343 * @see #FLAG_SUPPORTS_RECENTS 344 * @see #FLAG_SUPPORTS_SEARCH 345 */ 346 public static final String COLUMN_FLAGS = "flags"; 347 348 /** 349 * Icon resource ID for a root. This column is required. 350 * <p> 351 * Type: INTEGER (int) 352 */ 353 public static final String COLUMN_ICON = "icon"; 354 355 /** 356 * Title for a root, which will be shown to a user. This column is 357 * required. For a single storage service surfacing multiple accounts as 358 * different roots, this title should be the name of the service. 359 * <p> 360 * Type: STRING 361 */ 362 public static final String COLUMN_TITLE = "title"; 363 364 /** 365 * Summary for this root, which may be shown to a user. This column is 366 * optional, and may be {@code null}. For a single storage service 367 * surfacing multiple accounts as different roots, this summary should 368 * be the name of the account. 369 * <p> 370 * Type: STRING 371 */ 372 public static final String COLUMN_SUMMARY = "summary"; 373 374 /** 375 * Document which is a directory that represents the top directory of 376 * this root. This column is required. 377 * <p> 378 * Type: STRING 379 * 380 * @see Document#COLUMN_DOCUMENT_ID 381 */ 382 public static final String COLUMN_DOCUMENT_ID = "document_id"; 383 384 /** 385 * Number of bytes available in this root. This column is optional, and 386 * may be {@code null} if unknown or unbounded. 387 * <p> 388 * Type: INTEGER (long) 389 */ 390 public static final String COLUMN_AVAILABLE_BYTES = "available_bytes"; 391 392 /** 393 * MIME types supported by this root. This column is optional, and if 394 * {@code null} the root is assumed to support all MIME types. Multiple 395 * MIME types can be separated by a newline. For example, a root 396 * supporting audio might return "audio/*\napplication/x-flac". 397 * <p> 398 * Type: STRING 399 */ 400 public static final String COLUMN_MIME_TYPES = "mime_types"; 401 402 /** {@hide} */ 403 public static final String MIME_TYPE_ITEM = "vnd.android.document/root"; 404 405 /** 406 * Flag indicating that at least one directory under this root supports 407 * creating content. Roots with this flag will be shown when an 408 * application interacts with {@link Intent#ACTION_CREATE_DOCUMENT}. 409 * 410 * @see #COLUMN_FLAGS 411 */ 412 public static final int FLAG_SUPPORTS_CREATE = 1; 413 414 /** 415 * Flag indicating that this root offers content that is strictly local 416 * on the device. That is, no network requests are made for the content. 417 * 418 * @see #COLUMN_FLAGS 419 * @see Intent#EXTRA_LOCAL_ONLY 420 */ 421 public static final int FLAG_LOCAL_ONLY = 1 << 1; 422 423 /** 424 * Flag indicating that this root can be queried to provide recently 425 * modified documents. 426 * 427 * @see #COLUMN_FLAGS 428 * @see DocumentsContract#buildRecentDocumentsUri(String, String) 429 * @see DocumentsProvider#queryRecentDocuments(String, String[]) 430 */ 431 public static final int FLAG_SUPPORTS_RECENTS = 1 << 2; 432 433 /** 434 * Flag indicating that this root supports search. 435 * 436 * @see #COLUMN_FLAGS 437 * @see DocumentsContract#buildSearchDocumentsUri(String, String, 438 * String) 439 * @see DocumentsProvider#querySearchDocuments(String, String, 440 * String[]) 441 */ 442 public static final int FLAG_SUPPORTS_SEARCH = 1 << 3; 443 444 /** 445 * Flag indicating that this root supports testing parent child 446 * relationships. 447 * 448 * @see #COLUMN_FLAGS 449 * @see DocumentsProvider#isChildDocument(String, String) 450 */ 451 public static final int FLAG_SUPPORTS_IS_CHILD = 1 << 4; 452 453 /** 454 * Flag indicating that this root is currently empty. This may be used 455 * to hide the root when opening documents, but the root will still be 456 * shown when creating documents and {@link #FLAG_SUPPORTS_CREATE} is 457 * also set. If the value of this flag changes, such as when a root 458 * becomes non-empty, you must send a content changed notification for 459 * {@link DocumentsContract#buildRootsUri(String)}. 460 * 461 * @see #COLUMN_FLAGS 462 * @see ContentResolver#notifyChange(Uri, 463 * android.database.ContentObserver, boolean) 464 * @hide 465 */ 466 public static final int FLAG_EMPTY = 1 << 16; 467 468 /** 469 * Flag indicating that this root should only be visible to advanced 470 * users. 471 * 472 * @see #COLUMN_FLAGS 473 * @hide 474 */ 475 public static final int FLAG_ADVANCED = 1 << 17; 476 } 477 478 /** 479 * Optional boolean flag included in a directory {@link Cursor#getExtras()} 480 * indicating that a document provider is still loading data. For example, a 481 * provider has returned some results, but is still waiting on an 482 * outstanding network request. The provider must send a content changed 483 * notification when loading is finished. 484 * 485 * @see ContentResolver#notifyChange(Uri, android.database.ContentObserver, 486 * boolean) 487 */ 488 public static final String EXTRA_LOADING = "loading"; 489 490 /** 491 * Optional string included in a directory {@link Cursor#getExtras()} 492 * providing an informational message that should be shown to a user. For 493 * example, a provider may wish to indicate that not all documents are 494 * available. 495 */ 496 public static final String EXTRA_INFO = "info"; 497 498 /** 499 * Optional string included in a directory {@link Cursor#getExtras()} 500 * providing an error message that should be shown to a user. For example, a 501 * provider may wish to indicate that a network error occurred. The user may 502 * choose to retry, resulting in a new query. 503 */ 504 public static final String EXTRA_ERROR = "error"; 505 506 /** {@hide} */ 507 public static final String METHOD_CREATE_DOCUMENT = "android:createDocument"; 508 /** {@hide} */ 509 public static final String METHOD_RENAME_DOCUMENT = "android:renameDocument"; 510 /** {@hide} */ 511 public static final String METHOD_DELETE_DOCUMENT = "android:deleteDocument"; 512 513 /** {@hide} */ 514 public static final String EXTRA_THUMBNAIL_SIZE = "thumbnail_size"; 515 /** {@hide} */ 516 public static final String EXTRA_URI = "uri"; 517 518 private static final String PATH_ROOT = "root"; 519 private static final String PATH_RECENT = "recent"; 520 private static final String PATH_DOCUMENT = "document"; 521 private static final String PATH_CHILDREN = "children"; 522 private static final String PATH_SEARCH = "search"; 523 private static final String PATH_TREE = "tree"; 524 525 private static final String PARAM_QUERY = "query"; 526 private static final String PARAM_MANAGE = "manage"; 527 528 /** 529 * Build URI representing the roots of a document provider. When queried, a 530 * provider will return one or more rows with columns defined by 531 * {@link Root}. 532 * 533 * @see DocumentsProvider#queryRoots(String[]) 534 */ 535 public static Uri buildRootsUri(String authority) { 536 return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) 537 .authority(authority).appendPath(PATH_ROOT).build(); 538 } 539 540 /** 541 * Build URI representing the given {@link Root#COLUMN_ROOT_ID} in a 542 * document provider. 543 * 544 * @see #getRootId(Uri) 545 */ 546 public static Uri buildRootUri(String authority, String rootId) { 547 return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) 548 .authority(authority).appendPath(PATH_ROOT).appendPath(rootId).build(); 549 } 550 551 /** 552 * Build URI representing the recently modified documents of a specific root 553 * in a document provider. When queried, a provider will return zero or more 554 * rows with columns defined by {@link Document}. 555 * 556 * @see DocumentsProvider#queryRecentDocuments(String, String[]) 557 * @see #getRootId(Uri) 558 */ 559 public static Uri buildRecentDocumentsUri(String authority, String rootId) { 560 return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) 561 .authority(authority).appendPath(PATH_ROOT).appendPath(rootId) 562 .appendPath(PATH_RECENT).build(); 563 } 564 565 /** 566 * Build URI representing access to descendant documents of the given 567 * {@link Document#COLUMN_DOCUMENT_ID}. 568 * 569 * @see #getTreeDocumentId(Uri) 570 */ 571 public static Uri buildTreeDocumentUri(String authority, String documentId) { 572 return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority(authority) 573 .appendPath(PATH_TREE).appendPath(documentId).build(); 574 } 575 576 /** 577 * Build URI representing the target {@link Document#COLUMN_DOCUMENT_ID} in 578 * a document provider. When queried, a provider will return a single row 579 * with columns defined by {@link Document}. 580 * 581 * @see DocumentsProvider#queryDocument(String, String[]) 582 * @see #getDocumentId(Uri) 583 */ 584 public static Uri buildDocumentUri(String authority, String documentId) { 585 return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) 586 .authority(authority).appendPath(PATH_DOCUMENT).appendPath(documentId).build(); 587 } 588 589 /** 590 * Build URI representing the target {@link Document#COLUMN_DOCUMENT_ID} in 591 * a document provider. When queried, a provider will return a single row 592 * with columns defined by {@link Document}. 593 * <p> 594 * However, instead of directly accessing the target document, the returned 595 * URI will leverage access granted through a subtree URI, typically 596 * returned by {@link Intent#ACTION_OPEN_DOCUMENT_TREE}. The target document 597 * must be a descendant (child, grandchild, etc) of the subtree. 598 * <p> 599 * This is typically used to access documents under a user-selected 600 * directory tree, since it doesn't require the user to separately confirm 601 * each new document access. 602 * 603 * @param treeUri the subtree to leverage to gain access to the target 604 * document. The target directory must be a descendant of this 605 * subtree. 606 * @param documentId the target document, which the caller may not have 607 * direct access to. 608 * @see Intent#ACTION_OPEN_DOCUMENT_TREE 609 * @see DocumentsProvider#isChildDocument(String, String) 610 * @see #buildDocumentUri(String, String) 611 */ 612 public static Uri buildDocumentUriUsingTree(Uri treeUri, String documentId) { 613 return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) 614 .authority(treeUri.getAuthority()).appendPath(PATH_TREE) 615 .appendPath(getTreeDocumentId(treeUri)).appendPath(PATH_DOCUMENT) 616 .appendPath(documentId).build(); 617 } 618 619 /** {@hide} */ 620 public static Uri buildDocumentUriMaybeUsingTree(Uri baseUri, String documentId) { 621 if (isTreeUri(baseUri)) { 622 return buildDocumentUriUsingTree(baseUri, documentId); 623 } else { 624 return buildDocumentUri(baseUri.getAuthority(), documentId); 625 } 626 } 627 628 /** 629 * Build URI representing the children of the target directory in a document 630 * provider. When queried, a provider will return zero or more rows with 631 * columns defined by {@link Document}. 632 * 633 * @param parentDocumentId the document to return children for, which must 634 * be a directory with MIME type of 635 * {@link Document#MIME_TYPE_DIR}. 636 * @see DocumentsProvider#queryChildDocuments(String, String[], String) 637 * @see #getDocumentId(Uri) 638 */ 639 public static Uri buildChildDocumentsUri(String authority, String parentDocumentId) { 640 return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority(authority) 641 .appendPath(PATH_DOCUMENT).appendPath(parentDocumentId).appendPath(PATH_CHILDREN) 642 .build(); 643 } 644 645 /** 646 * Build URI representing the children of the target directory in a document 647 * provider. When queried, a provider will return zero or more rows with 648 * columns defined by {@link Document}. 649 * <p> 650 * However, instead of directly accessing the target directory, the returned 651 * URI will leverage access granted through a subtree URI, typically 652 * returned by {@link Intent#ACTION_OPEN_DOCUMENT_TREE}. The target 653 * directory must be a descendant (child, grandchild, etc) of the subtree. 654 * <p> 655 * This is typically used to access documents under a user-selected 656 * directory tree, since it doesn't require the user to separately confirm 657 * each new document access. 658 * 659 * @param treeUri the subtree to leverage to gain access to the target 660 * document. The target directory must be a descendant of this 661 * subtree. 662 * @param parentDocumentId the document to return children for, which the 663 * caller may not have direct access to, and which must be a 664 * directory with MIME type of {@link Document#MIME_TYPE_DIR}. 665 * @see Intent#ACTION_OPEN_DOCUMENT_TREE 666 * @see DocumentsProvider#isChildDocument(String, String) 667 * @see #buildChildDocumentsUri(String, String) 668 */ 669 public static Uri buildChildDocumentsUriUsingTree(Uri treeUri, String parentDocumentId) { 670 return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) 671 .authority(treeUri.getAuthority()).appendPath(PATH_TREE) 672 .appendPath(getTreeDocumentId(treeUri)).appendPath(PATH_DOCUMENT) 673 .appendPath(parentDocumentId).appendPath(PATH_CHILDREN).build(); 674 } 675 676 /** 677 * Build URI representing a search for matching documents under a specific 678 * root in a document provider. When queried, a provider will return zero or 679 * more rows with columns defined by {@link Document}. 680 * 681 * @see DocumentsProvider#querySearchDocuments(String, String, String[]) 682 * @see #getRootId(Uri) 683 * @see #getSearchDocumentsQuery(Uri) 684 */ 685 public static Uri buildSearchDocumentsUri( 686 String authority, String rootId, String query) { 687 return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority(authority) 688 .appendPath(PATH_ROOT).appendPath(rootId).appendPath(PATH_SEARCH) 689 .appendQueryParameter(PARAM_QUERY, query).build(); 690 } 691 692 /** 693 * Test if the given URI represents a {@link Document} backed by a 694 * {@link DocumentsProvider}. 695 * 696 * @see #buildDocumentUri(String, String) 697 * @see #buildDocumentUriUsingTree(Uri, String) 698 */ 699 public static boolean isDocumentUri(Context context, Uri uri) { 700 final List<String> paths = uri.getPathSegments(); 701 if (paths.size() == 2 && PATH_DOCUMENT.equals(paths.get(0))) { 702 return isDocumentsProvider(context, uri.getAuthority()); 703 } 704 if (paths.size() == 4 && PATH_TREE.equals(paths.get(0)) 705 && PATH_DOCUMENT.equals(paths.get(2))) { 706 return isDocumentsProvider(context, uri.getAuthority()); 707 } 708 return false; 709 } 710 711 /** {@hide} */ 712 public static boolean isTreeUri(Uri uri) { 713 final List<String> paths = uri.getPathSegments(); 714 return (paths.size() >= 2 && PATH_TREE.equals(paths.get(0))); 715 } 716 717 private static boolean isDocumentsProvider(Context context, String authority) { 718 final Intent intent = new Intent(PROVIDER_INTERFACE); 719 final List<ResolveInfo> infos = context.getPackageManager() 720 .queryIntentContentProviders(intent, 0); 721 for (ResolveInfo info : infos) { 722 if (authority.equals(info.providerInfo.authority)) { 723 return true; 724 } 725 } 726 return false; 727 } 728 729 /** 730 * Extract the {@link Root#COLUMN_ROOT_ID} from the given URI. 731 */ 732 public static String getRootId(Uri rootUri) { 733 final List<String> paths = rootUri.getPathSegments(); 734 if (paths.size() >= 2 && PATH_ROOT.equals(paths.get(0))) { 735 return paths.get(1); 736 } 737 throw new IllegalArgumentException("Invalid URI: " + rootUri); 738 } 739 740 /** 741 * Extract the {@link Document#COLUMN_DOCUMENT_ID} from the given URI. 742 * 743 * @see #isDocumentUri(Context, Uri) 744 */ 745 public static String getDocumentId(Uri documentUri) { 746 final List<String> paths = documentUri.getPathSegments(); 747 if (paths.size() >= 2 && PATH_DOCUMENT.equals(paths.get(0))) { 748 return paths.get(1); 749 } 750 if (paths.size() >= 4 && PATH_TREE.equals(paths.get(0)) 751 && PATH_DOCUMENT.equals(paths.get(2))) { 752 return paths.get(3); 753 } 754 throw new IllegalArgumentException("Invalid URI: " + documentUri); 755 } 756 757 /** 758 * Extract the via {@link Document#COLUMN_DOCUMENT_ID} from the given URI. 759 */ 760 public static String getTreeDocumentId(Uri documentUri) { 761 final List<String> paths = documentUri.getPathSegments(); 762 if (paths.size() >= 2 && PATH_TREE.equals(paths.get(0))) { 763 return paths.get(1); 764 } 765 throw new IllegalArgumentException("Invalid URI: " + documentUri); 766 } 767 768 /** 769 * Extract the search query from a URI built by 770 * {@link #buildSearchDocumentsUri(String, String, String)}. 771 */ 772 public static String getSearchDocumentsQuery(Uri searchDocumentsUri) { 773 return searchDocumentsUri.getQueryParameter(PARAM_QUERY); 774 } 775 776 /** {@hide} */ 777 public static Uri setManageMode(Uri uri) { 778 return uri.buildUpon().appendQueryParameter(PARAM_MANAGE, "true").build(); 779 } 780 781 /** {@hide} */ 782 public static boolean isManageMode(Uri uri) { 783 return uri.getBooleanQueryParameter(PARAM_MANAGE, false); 784 } 785 786 /** 787 * Return thumbnail representing the document at the given URI. Callers are 788 * responsible for their own in-memory caching. 789 * 790 * @param documentUri document to return thumbnail for, which must have 791 * {@link Document#FLAG_SUPPORTS_THUMBNAIL} set. 792 * @param size optimal thumbnail size desired. A provider may return a 793 * thumbnail of a different size, but never more than double the 794 * requested size. 795 * @param signal signal used to indicate if caller is no longer interested 796 * in the thumbnail. 797 * @return decoded thumbnail, or {@code null} if problem was encountered. 798 * @see DocumentsProvider#openDocumentThumbnail(String, Point, 799 * android.os.CancellationSignal) 800 */ 801 public static Bitmap getDocumentThumbnail( 802 ContentResolver resolver, Uri documentUri, Point size, CancellationSignal signal) { 803 final ContentProviderClient client = resolver.acquireUnstableContentProviderClient( 804 documentUri.getAuthority()); 805 try { 806 return getDocumentThumbnail(client, documentUri, size, signal); 807 } catch (Exception e) { 808 if (!(e instanceof OperationCanceledException)) { 809 Log.w(TAG, "Failed to load thumbnail for " + documentUri + ": " + e); 810 } 811 return null; 812 } finally { 813 ContentProviderClient.releaseQuietly(client); 814 } 815 } 816 817 /** {@hide} */ 818 public static Bitmap getDocumentThumbnail( 819 ContentProviderClient client, Uri documentUri, Point size, CancellationSignal signal) 820 throws RemoteException, IOException { 821 final Bundle openOpts = new Bundle(); 822 openOpts.putParcelable(DocumentsContract.EXTRA_THUMBNAIL_SIZE, size); 823 824 AssetFileDescriptor afd = null; 825 Bitmap bitmap = null; 826 try { 827 afd = client.openTypedAssetFileDescriptor(documentUri, "image/*", openOpts, signal); 828 829 final FileDescriptor fd = afd.getFileDescriptor(); 830 final long offset = afd.getStartOffset(); 831 832 // Try seeking on the returned FD, since it gives us the most 833 // optimal decode path; otherwise fall back to buffering. 834 BufferedInputStream is = null; 835 try { 836 Os.lseek(fd, offset, SEEK_SET); 837 } catch (ErrnoException e) { 838 is = new BufferedInputStream(new FileInputStream(fd), THUMBNAIL_BUFFER_SIZE); 839 is.mark(THUMBNAIL_BUFFER_SIZE); 840 } 841 842 // We requested a rough thumbnail size, but the remote size may have 843 // returned something giant, so defensively scale down as needed. 844 final BitmapFactory.Options opts = new BitmapFactory.Options(); 845 opts.inJustDecodeBounds = true; 846 if (is != null) { 847 BitmapFactory.decodeStream(is, null, opts); 848 } else { 849 BitmapFactory.decodeFileDescriptor(fd, null, opts); 850 } 851 852 final int widthSample = opts.outWidth / size.x; 853 final int heightSample = opts.outHeight / size.y; 854 855 opts.inJustDecodeBounds = false; 856 opts.inSampleSize = Math.min(widthSample, heightSample); 857 if (is != null) { 858 is.reset(); 859 bitmap = BitmapFactory.decodeStream(is, null, opts); 860 } else { 861 try { 862 Os.lseek(fd, offset, SEEK_SET); 863 } catch (ErrnoException e) { 864 e.rethrowAsIOException(); 865 } 866 bitmap = BitmapFactory.decodeFileDescriptor(fd, null, opts); 867 } 868 869 // Transform the bitmap if requested. We use a side-channel to 870 // communicate the orientation, since EXIF thumbnails don't contain 871 // the rotation flags of the original image. 872 final Bundle extras = afd.getExtras(); 873 final int orientation = (extras != null) ? extras.getInt(EXTRA_ORIENTATION, 0) : 0; 874 if (orientation != 0) { 875 final int width = bitmap.getWidth(); 876 final int height = bitmap.getHeight(); 877 878 final Matrix m = new Matrix(); 879 m.setRotate(orientation, width / 2, height / 2); 880 bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, false); 881 } 882 } finally { 883 IoUtils.closeQuietly(afd); 884 } 885 886 return bitmap; 887 } 888 889 /** 890 * Create a new document with given MIME type and display name. 891 * 892 * @param parentDocumentUri directory with 893 * {@link Document#FLAG_DIR_SUPPORTS_CREATE} 894 * @param mimeType MIME type of new document 895 * @param displayName name of new document 896 * @return newly created document, or {@code null} if failed 897 */ 898 public static Uri createDocument(ContentResolver resolver, Uri parentDocumentUri, 899 String mimeType, String displayName) { 900 final ContentProviderClient client = resolver.acquireUnstableContentProviderClient( 901 parentDocumentUri.getAuthority()); 902 try { 903 return createDocument(client, parentDocumentUri, mimeType, displayName); 904 } catch (Exception e) { 905 Log.w(TAG, "Failed to create document", e); 906 return null; 907 } finally { 908 ContentProviderClient.releaseQuietly(client); 909 } 910 } 911 912 /** {@hide} */ 913 public static Uri createDocument(ContentProviderClient client, Uri parentDocumentUri, 914 String mimeType, String displayName) throws RemoteException { 915 final Bundle in = new Bundle(); 916 in.putParcelable(DocumentsContract.EXTRA_URI, parentDocumentUri); 917 in.putString(Document.COLUMN_MIME_TYPE, mimeType); 918 in.putString(Document.COLUMN_DISPLAY_NAME, displayName); 919 920 final Bundle out = client.call(METHOD_CREATE_DOCUMENT, null, in); 921 return out.getParcelable(DocumentsContract.EXTRA_URI); 922 } 923 924 /** 925 * Change the display name of an existing document. 926 * <p> 927 * If the underlying provider needs to create a new 928 * {@link Document#COLUMN_DOCUMENT_ID} to represent the updated display 929 * name, that new document is returned and the original document is no 930 * longer valid. Otherwise, the original document is returned. 931 * 932 * @param documentUri document with {@link Document#FLAG_SUPPORTS_RENAME} 933 * @param displayName updated name for document 934 * @return the existing or new document after the rename, or {@code null} if 935 * failed. 936 */ 937 public static Uri renameDocument(ContentResolver resolver, Uri documentUri, 938 String displayName) { 939 final ContentProviderClient client = resolver.acquireUnstableContentProviderClient( 940 documentUri.getAuthority()); 941 try { 942 return renameDocument(client, documentUri, displayName); 943 } catch (Exception e) { 944 Log.w(TAG, "Failed to rename document", e); 945 return null; 946 } finally { 947 ContentProviderClient.releaseQuietly(client); 948 } 949 } 950 951 /** {@hide} */ 952 public static Uri renameDocument(ContentProviderClient client, Uri documentUri, 953 String displayName) throws RemoteException { 954 final Bundle in = new Bundle(); 955 in.putParcelable(DocumentsContract.EXTRA_URI, documentUri); 956 in.putString(Document.COLUMN_DISPLAY_NAME, displayName); 957 958 final Bundle out = client.call(METHOD_RENAME_DOCUMENT, null, in); 959 final Uri outUri = out.getParcelable(DocumentsContract.EXTRA_URI); 960 return (outUri != null) ? outUri : documentUri; 961 } 962 963 /** 964 * Delete the given document. 965 * 966 * @param documentUri document with {@link Document#FLAG_SUPPORTS_DELETE} 967 * @return if the document was deleted successfully. 968 */ 969 public static boolean deleteDocument(ContentResolver resolver, Uri documentUri) { 970 final ContentProviderClient client = resolver.acquireUnstableContentProviderClient( 971 documentUri.getAuthority()); 972 try { 973 deleteDocument(client, documentUri); 974 return true; 975 } catch (Exception e) { 976 Log.w(TAG, "Failed to delete document", e); 977 return false; 978 } finally { 979 ContentProviderClient.releaseQuietly(client); 980 } 981 } 982 983 /** {@hide} */ 984 public static void deleteDocument(ContentProviderClient client, Uri documentUri) 985 throws RemoteException { 986 final Bundle in = new Bundle(); 987 in.putParcelable(DocumentsContract.EXTRA_URI, documentUri); 988 989 client.call(METHOD_DELETE_DOCUMENT, null, in); 990 } 991 992 /** 993 * Open the given image for thumbnail purposes, using any embedded EXIF 994 * thumbnail if available, and providing orientation hints from the parent 995 * image. 996 * 997 * @hide 998 */ 999 public static AssetFileDescriptor openImageThumbnail(File file) throws FileNotFoundException { 1000 final ParcelFileDescriptor pfd = ParcelFileDescriptor.open( 1001 file, ParcelFileDescriptor.MODE_READ_ONLY); 1002 Bundle extras = null; 1003 1004 try { 1005 final ExifInterface exif = new ExifInterface(file.getAbsolutePath()); 1006 1007 switch (exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1)) { 1008 case ExifInterface.ORIENTATION_ROTATE_90: 1009 extras = new Bundle(1); 1010 extras.putInt(EXTRA_ORIENTATION, 90); 1011 break; 1012 case ExifInterface.ORIENTATION_ROTATE_180: 1013 extras = new Bundle(1); 1014 extras.putInt(EXTRA_ORIENTATION, 180); 1015 break; 1016 case ExifInterface.ORIENTATION_ROTATE_270: 1017 extras = new Bundle(1); 1018 extras.putInt(EXTRA_ORIENTATION, 270); 1019 break; 1020 } 1021 1022 final long[] thumb = exif.getThumbnailRange(); 1023 if (thumb != null) { 1024 return new AssetFileDescriptor(pfd, thumb[0], thumb[1], extras); 1025 } 1026 } catch (IOException e) { 1027 } 1028 1029 return new AssetFileDescriptor(pfd, 0, AssetFileDescriptor.UNKNOWN_LENGTH, extras); 1030 } 1031} 1032