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