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