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 17 package android.provider; 18 19 import static com.android.internal.util.Preconditions.checkCollectionElementsNotNull; 20 import static com.android.internal.util.Preconditions.checkCollectionNotEmpty; 21 22 import android.annotation.NonNull; 23 import android.annotation.Nullable; 24 import android.annotation.SystemApi; 25 import android.annotation.TestApi; 26 import android.compat.annotation.UnsupportedAppUsage; 27 import android.content.ContentProvider; 28 import android.content.ContentResolver; 29 import android.content.Context; 30 import android.content.Intent; 31 import android.content.IntentSender; 32 import android.content.MimeTypeFilter; 33 import android.content.pm.ResolveInfo; 34 import android.content.res.AssetFileDescriptor; 35 import android.database.Cursor; 36 import android.graphics.Bitmap; 37 import android.graphics.ImageDecoder; 38 import android.graphics.Point; 39 import android.media.ExifInterface; 40 import android.net.Uri; 41 import android.os.Build; 42 import android.os.Bundle; 43 import android.os.CancellationSignal; 44 import android.os.OperationCanceledException; 45 import android.os.Parcel; 46 import android.os.ParcelFileDescriptor; 47 import android.os.ParcelFileDescriptor.OnCloseListener; 48 import android.os.Parcelable; 49 import android.os.ParcelableException; 50 import android.os.RemoteException; 51 import android.os.UserHandle; 52 import android.util.Log; 53 54 import com.android.internal.util.Preconditions; 55 56 import dalvik.system.VMRuntime; 57 58 import java.io.File; 59 import java.io.FileNotFoundException; 60 import java.io.IOException; 61 import java.util.ArrayList; 62 import java.util.List; 63 import java.util.Objects; 64 65 /** 66 * Defines the contract between a documents provider and the platform. 67 * <p> 68 * To create a document provider, extend {@link DocumentsProvider}, which 69 * provides a foundational implementation of this contract. 70 * <p> 71 * All client apps must hold a valid URI permission grant to access documents, 72 * typically issued when a user makes a selection through 73 * {@link Intent#ACTION_OPEN_DOCUMENT}, {@link Intent#ACTION_CREATE_DOCUMENT}, 74 * or {@link Intent#ACTION_OPEN_DOCUMENT_TREE}. 75 * 76 * @see DocumentsProvider 77 */ 78 public final class DocumentsContract { 79 private static final String TAG = "DocumentsContract"; 80 81 // content://com.example/root/ 82 // content://com.example/root/sdcard/ 83 // content://com.example/root/sdcard/recent/ 84 // content://com.example/root/sdcard/search/?query=pony 85 // content://com.example/document/12/ 86 // content://com.example/document/12/children/ 87 // content://com.example/tree/12/document/24/ 88 // content://com.example/tree/12/document/24/children/ 89 DocumentsContract()90 private DocumentsContract() { 91 } 92 93 /** 94 * Intent action used to identify {@link DocumentsProvider} instances. This 95 * is used in the {@code <intent-filter>} of a {@code <provider>}. 96 */ 97 public static final String PROVIDER_INTERFACE = "android.content.action.DOCUMENTS_PROVIDER"; 98 99 /** {@hide} */ 100 @Deprecated 101 public static final String EXTRA_PACKAGE_NAME = Intent.EXTRA_PACKAGE_NAME; 102 103 /** 104 * The value is decide whether to show advance mode or not. 105 * If the value is true, the local/device storage root must be 106 * visible in DocumentsUI. 107 * 108 * {@hide} 109 */ 110 @SystemApi 111 public static final String EXTRA_SHOW_ADVANCED = "android.provider.extra.SHOW_ADVANCED"; 112 113 /** {@hide} */ 114 public static final String EXTRA_TARGET_URI = "android.content.extra.TARGET_URI"; 115 116 /** 117 * Key for {@link DocumentsProvider} to query display name is matched. 118 * The match of display name is partial matching and case-insensitive. 119 * Ex: The value is "o", the display name of the results will contain 120 * both "foo" and "Open". 121 * 122 * @see DocumentsProvider#querySearchDocuments(String, String[], 123 * Bundle) 124 */ 125 public static final String QUERY_ARG_DISPLAY_NAME = "android:query-arg-display-name"; 126 127 /** 128 * Key for {@link DocumentsProvider} to query mime types is matched. 129 * The value is a string array, it can support different mime types. 130 * Each items will be treated as "OR" condition. Ex: {"image/*" , 131 * "video/*"}. The mime types of the results will contain both image 132 * type and video type. 133 * 134 * @see DocumentsProvider#querySearchDocuments(String, String[], 135 * Bundle) 136 */ 137 public static final String QUERY_ARG_MIME_TYPES = "android:query-arg-mime-types"; 138 139 /** 140 * Key for {@link DocumentsProvider} to query the file size in bytes is 141 * larger than the value. 142 * 143 * @see DocumentsProvider#querySearchDocuments(String, String[], 144 * Bundle) 145 */ 146 public static final String QUERY_ARG_FILE_SIZE_OVER = "android:query-arg-file-size-over"; 147 148 /** 149 * Key for {@link DocumentsProvider} to query the last modified time 150 * is newer than the value. The unit is in milliseconds since 151 * January 1, 1970 00:00:00.0 UTC. 152 * 153 * @see DocumentsProvider#querySearchDocuments(String, String[], 154 * Bundle) 155 * @see Document#COLUMN_LAST_MODIFIED 156 */ 157 public static final String QUERY_ARG_LAST_MODIFIED_AFTER = 158 "android:query-arg-last-modified-after"; 159 160 /** 161 * Key for {@link DocumentsProvider} to decide whether the files that 162 * have been added to MediaStore should be excluded. If the value is 163 * true, exclude them. Otherwise, include them. 164 * 165 * @see DocumentsProvider#querySearchDocuments(String, String[], 166 * Bundle) 167 */ 168 public static final String QUERY_ARG_EXCLUDE_MEDIA = "android:query-arg-exclude-media"; 169 170 /** 171 * Sets the desired initial location visible to user when file chooser is shown. 172 * 173 * <p>Applicable to {@link Intent} with actions: 174 * <ul> 175 * <li>{@link Intent#ACTION_OPEN_DOCUMENT}</li> 176 * <li>{@link Intent#ACTION_CREATE_DOCUMENT}</li> 177 * <li>{@link Intent#ACTION_OPEN_DOCUMENT_TREE}</li> 178 * </ul> 179 * 180 * <p>Location should specify a document URI or a tree URI with document ID. If 181 * this URI identifies a non-directory, document navigator will attempt to use the parent 182 * of the document as the initial location. 183 * 184 * <p>The initial location is system specific if this extra is missing or document navigator 185 * failed to locate the desired initial location. 186 */ 187 public static final String EXTRA_INITIAL_URI = "android.provider.extra.INITIAL_URI"; 188 189 /** 190 * Set this in a DocumentsUI intent to cause a package's own roots to be 191 * excluded from the roots list. 192 */ 193 public static final String EXTRA_EXCLUDE_SELF = "android.provider.extra.EXCLUDE_SELF"; 194 195 /** 196 * An extra number of degrees that an image should be rotated during the 197 * decode process to be presented correctly. 198 * 199 * @see AssetFileDescriptor#getExtras() 200 * @see android.provider.MediaStore.Images.ImageColumns#ORIENTATION 201 */ 202 public static final String EXTRA_ORIENTATION = "android.provider.extra.ORIENTATION"; 203 204 /** 205 * Overrides the default prompt text in DocumentsUI when set in an intent. 206 */ 207 public static final String EXTRA_PROMPT = "android.provider.extra.PROMPT"; 208 209 /** 210 * Action of intent issued by DocumentsUI when user wishes to open/configure/manage a particular 211 * document in the provider application. 212 * 213 * <p>When issued, the intent will include the URI of the document as the intent data. 214 * 215 * <p>A provider wishing to provide support for this action should do two things. 216 * <li>Add an {@code <intent-filter>} matching this action. 217 * <li>When supplying information in {@link DocumentsProvider#queryChildDocuments}, include 218 * {@link Document#FLAG_SUPPORTS_SETTINGS} in the flags for each document that supports 219 * settings. 220 */ 221 public static final String 222 ACTION_DOCUMENT_SETTINGS = "android.provider.action.DOCUMENT_SETTINGS"; 223 224 /** 225 * The action to manage document in Downloads root in DocumentsUI. 226 * {@hide} 227 */ 228 @SystemApi 229 public static final String ACTION_MANAGE_DOCUMENT = "android.provider.action.MANAGE_DOCUMENT"; 230 231 /** 232 * The action to launch the settings of this root. 233 * {@hide} 234 */ 235 @SystemApi 236 public static final String 237 ACTION_DOCUMENT_ROOT_SETTINGS = "android.provider.action.DOCUMENT_ROOT_SETTINGS"; 238 239 /** {@hide} */ 240 public static final String EXTERNAL_STORAGE_PROVIDER_AUTHORITY = 241 "com.android.externalstorage.documents"; 242 243 /** {@hide} */ 244 public static final String EXTERNAL_STORAGE_PRIMARY_EMULATED_ROOT_ID = "primary"; 245 246 /** {@hide} */ 247 public static final String PACKAGE_DOCUMENTS_UI = "com.android.documentsui"; 248 249 /** 250 * Get string array identifies the type or types of metadata returned 251 * using DocumentsContract#getDocumentMetadata. 252 * 253 * @see #getDocumentMetadata(ContentResolver, Uri) 254 */ 255 public static final String METADATA_TYPES = "android:documentMetadataTypes"; 256 257 /** 258 * Get Exif information using DocumentsContract#getDocumentMetadata. 259 * 260 * @see #getDocumentMetadata(ContentResolver, Uri) 261 */ 262 public static final String METADATA_EXIF = "android:documentExif"; 263 264 /** 265 * Get total count of all documents currently stored under the given 266 * directory tree. Only valid for {@link Document#MIME_TYPE_DIR} documents. 267 * 268 * @see #getDocumentMetadata(ContentResolver, Uri) 269 */ 270 public static final String METADATA_TREE_COUNT = "android:metadataTreeCount"; 271 272 /** 273 * Get total size of all documents currently stored under the given 274 * directory tree. Only valid for {@link Document#MIME_TYPE_DIR} documents. 275 * 276 * @see #getDocumentMetadata(ContentResolver, Uri) 277 */ 278 public static final String METADATA_TREE_SIZE = "android:metadataTreeSize"; 279 280 /** 281 * Constants related to a document, including {@link Cursor} column names 282 * and flags. 283 * <p> 284 * A document can be either an openable stream (with a specific MIME type), 285 * or a directory containing additional documents (with the 286 * {@link #MIME_TYPE_DIR} MIME type). A directory represents the top of a 287 * subtree containing zero or more documents, which can recursively contain 288 * even more documents and directories. 289 * <p> 290 * All columns are <em>read-only</em> to client applications. 291 */ 292 public final static class Document { Document()293 private Document() { 294 } 295 296 /** 297 * Unique ID of a document. This ID is both provided by and interpreted 298 * by a {@link DocumentsProvider}, and should be treated as an opaque 299 * value by client applications. This column is required. 300 * <p> 301 * Each document must have a unique ID within a provider, but that 302 * single document may be included as a child of multiple directories. 303 * <p> 304 * A provider must always return durable IDs, since they will be used to 305 * issue long-term URI permission grants when an application interacts 306 * with {@link Intent#ACTION_OPEN_DOCUMENT} and 307 * {@link Intent#ACTION_CREATE_DOCUMENT}. 308 * <p> 309 * Type: STRING 310 */ 311 public static final String COLUMN_DOCUMENT_ID = "document_id"; 312 313 /** 314 * Concrete MIME type of a document. For example, "image/png" or 315 * "application/pdf" for openable files. A document can also be a 316 * directory containing additional documents, which is represented with 317 * the {@link #MIME_TYPE_DIR} MIME type. This column is required. 318 * <p> 319 * Type: STRING 320 * 321 * @see #MIME_TYPE_DIR 322 */ 323 public static final String COLUMN_MIME_TYPE = "mime_type"; 324 325 /** 326 * Display name of a document, used as the primary title displayed to a 327 * user. This column is required. 328 * <p> 329 * Type: STRING 330 */ 331 public static final String COLUMN_DISPLAY_NAME = OpenableColumns.DISPLAY_NAME; 332 333 /** 334 * Summary of a document, which may be shown to a user. This column is 335 * optional, and may be {@code null}. 336 * <p> 337 * Type: STRING 338 */ 339 public static final String COLUMN_SUMMARY = "summary"; 340 341 /** 342 * Timestamp when a document was last modified, in milliseconds since 343 * January 1, 1970 00:00:00.0 UTC. This column is required, and may be 344 * {@code null} if unknown. A {@link DocumentsProvider} can update this 345 * field using events from {@link OnCloseListener} or other reliable 346 * {@link ParcelFileDescriptor} transports. 347 * <p> 348 * Type: INTEGER (long) 349 * 350 * @see System#currentTimeMillis() 351 */ 352 public static final String COLUMN_LAST_MODIFIED = "last_modified"; 353 354 /** 355 * Specific icon resource ID for a document. This column is optional, 356 * and may be {@code null} to use a platform-provided default icon based 357 * on {@link #COLUMN_MIME_TYPE}. 358 * <p> 359 * Type: INTEGER (int) 360 */ 361 public static final String COLUMN_ICON = "icon"; 362 363 /** 364 * Flags that apply to a document. This column is required. 365 * <p> 366 * Type: INTEGER (int) 367 * 368 * @see #FLAG_DIR_BLOCKS_OPEN_DOCUMENT_TREE 369 * @see #FLAG_DIR_PREFERS_GRID 370 * @see #FLAG_DIR_PREFERS_LAST_MODIFIED 371 * @see #FLAG_DIR_SUPPORTS_CREATE 372 * @see #FLAG_PARTIAL 373 * @see #FLAG_SUPPORTS_COPY 374 * @see #FLAG_SUPPORTS_DELETE 375 * @see #FLAG_SUPPORTS_METADATA 376 * @see #FLAG_SUPPORTS_MOVE 377 * @see #FLAG_SUPPORTS_REMOVE 378 * @see #FLAG_SUPPORTS_RENAME 379 * @see #FLAG_SUPPORTS_SETTINGS 380 * @see #FLAG_SUPPORTS_THUMBNAIL 381 * @see #FLAG_SUPPORTS_WRITE 382 * @see #FLAG_VIRTUAL_DOCUMENT 383 * @see #FLAG_WEB_LINKABLE 384 */ 385 public static final String COLUMN_FLAGS = "flags"; 386 387 /** 388 * Size of a document, in bytes, or {@code null} if unknown. This column 389 * is required. 390 * <p> 391 * Type: INTEGER (long) 392 */ 393 public static final String COLUMN_SIZE = OpenableColumns.SIZE; 394 395 /** 396 * MIME type of a document which is a directory that may contain 397 * additional documents. 398 * 399 * @see #COLUMN_MIME_TYPE 400 */ 401 public static final String MIME_TYPE_DIR = "vnd.android.document/directory"; 402 403 /** 404 * Flag indicating that a document can be represented as a thumbnail. 405 * 406 * @see #COLUMN_FLAGS 407 * @see DocumentsContract#getDocumentThumbnail(ContentResolver, Uri, 408 * Point, CancellationSignal) 409 * @see DocumentsProvider#openDocumentThumbnail(String, Point, 410 * android.os.CancellationSignal) 411 */ 412 public static final int FLAG_SUPPORTS_THUMBNAIL = 1; 413 414 /** 415 * Flag indicating that a document supports writing. 416 * <p> 417 * When a document is opened with {@link Intent#ACTION_OPEN_DOCUMENT}, 418 * the calling application is granted both 419 * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and 420 * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}. However, the actual 421 * writability of a document may change over time, for example due to 422 * remote access changes. This flag indicates that a document client can 423 * expect {@link ContentResolver#openOutputStream(Uri)} to succeed. 424 * 425 * @see #COLUMN_FLAGS 426 */ 427 public static final int FLAG_SUPPORTS_WRITE = 1 << 1; 428 429 /** 430 * Flag indicating that a document is deletable. 431 * 432 * @see #COLUMN_FLAGS 433 * @see DocumentsContract#deleteDocument(ContentResolver, Uri) 434 * @see DocumentsProvider#deleteDocument(String) 435 */ 436 public static final int FLAG_SUPPORTS_DELETE = 1 << 2; 437 438 /** 439 * Flag indicating that a document is a directory that supports creation 440 * of new files within it. Only valid when {@link #COLUMN_MIME_TYPE} is 441 * {@link #MIME_TYPE_DIR}. 442 * 443 * @see #COLUMN_FLAGS 444 * @see DocumentsProvider#createDocument(String, String, String) 445 */ 446 public static final int FLAG_DIR_SUPPORTS_CREATE = 1 << 3; 447 448 /** 449 * Flag indicating that a directory prefers its contents be shown in a 450 * larger format grid. Usually suitable when a directory contains mostly 451 * pictures. Only valid when {@link #COLUMN_MIME_TYPE} is 452 * {@link #MIME_TYPE_DIR}. 453 * 454 * @see #COLUMN_FLAGS 455 */ 456 public static final int FLAG_DIR_PREFERS_GRID = 1 << 4; 457 458 /** 459 * Flag indicating that a directory prefers its contents be sorted by 460 * {@link #COLUMN_LAST_MODIFIED}. Only valid when 461 * {@link #COLUMN_MIME_TYPE} is {@link #MIME_TYPE_DIR}. 462 * 463 * @see #COLUMN_FLAGS 464 */ 465 public static final int FLAG_DIR_PREFERS_LAST_MODIFIED = 1 << 5; 466 467 /** 468 * Flag indicating that a document can be renamed. 469 * 470 * @see #COLUMN_FLAGS 471 * @see DocumentsContract#renameDocument(ContentResolver, Uri, String) 472 * @see DocumentsProvider#renameDocument(String, String) 473 */ 474 public static final int FLAG_SUPPORTS_RENAME = 1 << 6; 475 476 /** 477 * Flag indicating that a document can be copied to another location 478 * within the same document provider. 479 * 480 * @see #COLUMN_FLAGS 481 * @see DocumentsContract#copyDocument(ContentResolver, Uri, Uri) 482 * @see DocumentsProvider#copyDocument(String, String) 483 */ 484 public static final int FLAG_SUPPORTS_COPY = 1 << 7; 485 486 /** 487 * Flag indicating that a document can be moved to another location 488 * within the same document provider. 489 * 490 * @see #COLUMN_FLAGS 491 * @see DocumentsContract#moveDocument(ContentResolver, Uri, Uri, Uri) 492 * @see DocumentsProvider#moveDocument(String, String, String) 493 */ 494 public static final int FLAG_SUPPORTS_MOVE = 1 << 8; 495 496 /** 497 * Flag indicating that a document is virtual, and doesn't have byte 498 * representation in the MIME type specified as {@link #COLUMN_MIME_TYPE}. 499 * 500 * <p><em>Virtual documents must have at least one alternative streamable 501 * format via {@link DocumentsProvider#openTypedDocument}</em> 502 * 503 * @see #COLUMN_FLAGS 504 * @see #COLUMN_MIME_TYPE 505 * @see DocumentsProvider#openTypedDocument(String, String, Bundle, 506 * android.os.CancellationSignal) 507 * @see DocumentsProvider#getDocumentStreamTypes(String, String) 508 */ 509 public static final int FLAG_VIRTUAL_DOCUMENT = 1 << 9; 510 511 /** 512 * Flag indicating that a document can be removed from a parent. 513 * 514 * @see #COLUMN_FLAGS 515 * @see DocumentsContract#removeDocument(ContentResolver, Uri, Uri) 516 * @see DocumentsProvider#removeDocument(String, String) 517 */ 518 public static final int FLAG_SUPPORTS_REMOVE = 1 << 10; 519 520 /** 521 * Flag indicating that a document has settings that can be configured by user. 522 * 523 * @see #COLUMN_FLAGS 524 * @see #ACTION_DOCUMENT_SETTINGS 525 */ 526 public static final int FLAG_SUPPORTS_SETTINGS = 1 << 11; 527 528 /** 529 * Flag indicating that a Web link can be obtained for the document. 530 * 531 * @see #COLUMN_FLAGS 532 * @see DocumentsProvider#createWebLinkIntent(String, Bundle) 533 */ 534 public static final int FLAG_WEB_LINKABLE = 1 << 12; 535 536 /** 537 * Flag indicating that a document is not complete, likely its 538 * contents are being downloaded. Partial files cannot be opened, 539 * copied, moved in the UI. But they can be deleted and retried 540 * if they represent a failed download. 541 * 542 * @see #COLUMN_FLAGS 543 */ 544 public static final int FLAG_PARTIAL = 1 << 13; 545 546 /** 547 * Flag indicating that a document has available metadata that can be read 548 * using DocumentsContract#getDocumentMetadata 549 * 550 * @see #COLUMN_FLAGS 551 * @see DocumentsContract#getDocumentMetadata(ContentResolver, Uri) 552 */ 553 public static final int FLAG_SUPPORTS_METADATA = 1 << 14; 554 555 /** 556 * Flag indicating that a document is a directory that wants to block itself 557 * from being selected when the user launches an {@link Intent#ACTION_OPEN_DOCUMENT_TREE} 558 * intent. Individual files can still be selected when launched via other intents 559 * like {@link Intent#ACTION_OPEN_DOCUMENT} and {@link Intent#ACTION_GET_CONTENT}. 560 * Only valid when {@link #COLUMN_MIME_TYPE} is {@link #MIME_TYPE_DIR}. 561 * <p> 562 * Note that this flag <em>only</em> applies to the single directory to which it is 563 * applied. It does <em>not</em> block the user from selecting either a parent or 564 * child directory during an {@link Intent#ACTION_OPEN_DOCUMENT_TREE} request. 565 * In particular, the only way to guarantee that a specific directory can never 566 * be granted via an {@link Intent#ACTION_OPEN_DOCUMENT_TREE} request is to ensure 567 * that both it and <em>all of its parent directories</em> have set this flag. 568 * 569 * @see Intent#ACTION_OPEN_DOCUMENT_TREE 570 * @see #COLUMN_FLAGS 571 */ 572 public static final int FLAG_DIR_BLOCKS_OPEN_DOCUMENT_TREE = 1 << 15; 573 } 574 575 /** 576 * Constants related to a root of documents, including {@link Cursor} column 577 * names and flags. A root is the start of a tree of documents, such as a 578 * physical storage device, or an account. Each root starts at the directory 579 * referenced by {@link Root#COLUMN_DOCUMENT_ID}, which can recursively 580 * contain both documents and directories. 581 * <p> 582 * All columns are <em>read-only</em> to client applications. 583 */ 584 public final static class Root { Root()585 private Root() { 586 } 587 588 /** 589 * Unique ID of a root. This ID is both provided by and interpreted by a 590 * {@link DocumentsProvider}, and should be treated as an opaque value 591 * by client applications. This column is required. 592 * <p> 593 * Type: STRING 594 */ 595 public static final String COLUMN_ROOT_ID = "root_id"; 596 597 /** 598 * Flags that apply to a root. This column is required. 599 * <p> 600 * Type: INTEGER (int) 601 * 602 * @see #FLAG_LOCAL_ONLY 603 * @see #FLAG_SUPPORTS_CREATE 604 * @see #FLAG_SUPPORTS_RECENTS 605 * @see #FLAG_SUPPORTS_SEARCH 606 */ 607 public static final String COLUMN_FLAGS = "flags"; 608 609 /** 610 * Icon resource ID for a root. This column is required. 611 * <p> 612 * Type: INTEGER (int) 613 */ 614 public static final String COLUMN_ICON = "icon"; 615 616 /** 617 * Title for a root, which will be shown to a user. This column is 618 * required. For a single storage service surfacing multiple accounts as 619 * different roots, this title should be the name of the service. 620 * <p> 621 * Type: STRING 622 */ 623 public static final String COLUMN_TITLE = "title"; 624 625 /** 626 * Summary for this root, which may be shown to a user. This column is 627 * optional, and may be {@code null}. For a single storage service 628 * surfacing multiple accounts as different roots, this summary should 629 * be the name of the account. 630 * <p> 631 * Type: STRING 632 */ 633 public static final String COLUMN_SUMMARY = "summary"; 634 635 /** 636 * Document which is a directory that represents the top directory of 637 * this root. This column is required. 638 * <p> 639 * Type: STRING 640 * 641 * @see Document#COLUMN_DOCUMENT_ID 642 */ 643 public static final String COLUMN_DOCUMENT_ID = "document_id"; 644 645 /** 646 * Number of bytes available in this root. This column is optional, and 647 * may be {@code null} if unknown or unbounded. 648 * <p> 649 * Type: INTEGER (long) 650 */ 651 public static final String COLUMN_AVAILABLE_BYTES = "available_bytes"; 652 653 /** 654 * Capacity of a root in bytes. This column is optional, and may be 655 * {@code null} if unknown or unbounded. 656 * <p> 657 * Type: INTEGER (long) 658 */ 659 public static final String COLUMN_CAPACITY_BYTES = "capacity_bytes"; 660 661 /** 662 * MIME types supported by this root. This column is optional, and if 663 * {@code null} the root is assumed to support all MIME types. Multiple 664 * MIME types can be separated by a newline. For example, a root 665 * supporting audio might return "audio/*\napplication/x-flac". 666 * <p> 667 * Type: STRING 668 */ 669 public static final String COLUMN_MIME_TYPES = "mime_types"; 670 671 /** 672 * Query arguments supported by this root. This column is optional 673 * and related to {@link #COLUMN_FLAGS} and {@link #FLAG_SUPPORTS_SEARCH}. 674 * If the flags include {@link #FLAG_SUPPORTS_SEARCH}, and the column is 675 * {@code null}, the root is assumed to support {@link #QUERY_ARG_DISPLAY_NAME} 676 * search of {@link Document#COLUMN_DISPLAY_NAME}. Multiple query arguments 677 * can be separated by a newline. For example, a root supporting 678 * {@link #QUERY_ARG_MIME_TYPES} and {@link #QUERY_ARG_DISPLAY_NAME} might 679 * return "android:query-arg-mime-types\nandroid:query-arg-display-name". 680 * <p> 681 * Type: STRING 682 * @see #COLUMN_FLAGS 683 * @see #FLAG_SUPPORTS_SEARCH 684 * @see #QUERY_ARG_DISPLAY_NAME 685 * @see #QUERY_ARG_FILE_SIZE_OVER 686 * @see #QUERY_ARG_LAST_MODIFIED_AFTER 687 * @see #QUERY_ARG_MIME_TYPES 688 * @see DocumentsProvider#querySearchDocuments(String, String[], 689 * Bundle) 690 */ 691 public static final String COLUMN_QUERY_ARGS = "query_args"; 692 693 /** 694 * MIME type for a root. 695 */ 696 public static final String MIME_TYPE_ITEM = "vnd.android.document/root"; 697 698 /** 699 * Flag indicating that at least one directory under this root supports 700 * creating content. Roots with this flag will be shown when an 701 * application interacts with {@link Intent#ACTION_CREATE_DOCUMENT}. 702 * 703 * @see #COLUMN_FLAGS 704 */ 705 public static final int FLAG_SUPPORTS_CREATE = 1; 706 707 /** 708 * Flag indicating that this root offers content that is strictly local 709 * on the device. That is, no network requests are made for the content. 710 * 711 * @see #COLUMN_FLAGS 712 * @see Intent#EXTRA_LOCAL_ONLY 713 */ 714 public static final int FLAG_LOCAL_ONLY = 1 << 1; 715 716 /** 717 * Flag indicating that this root can be queried to provide recently 718 * modified documents. 719 * 720 * @see #COLUMN_FLAGS 721 * @see DocumentsContract#buildRecentDocumentsUri(String, String) 722 * @see DocumentsProvider#queryRecentDocuments(String, String[]) 723 */ 724 public static final int FLAG_SUPPORTS_RECENTS = 1 << 2; 725 726 /** 727 * Flag indicating that this root supports search. 728 * 729 * @see #COLUMN_FLAGS 730 * @see DocumentsContract#buildSearchDocumentsUri(String, String, 731 * String) 732 * @see DocumentsProvider#querySearchDocuments(String, String, 733 * String[]) 734 * @see DocumentsProvider#querySearchDocuments(String, String[], 735 * Bundle) 736 */ 737 public static final int FLAG_SUPPORTS_SEARCH = 1 << 3; 738 739 /** 740 * Flag indicating that this root supports testing parent child 741 * relationships. 742 * 743 * @see #COLUMN_FLAGS 744 * @see DocumentsProvider#isChildDocument(String, String) 745 */ 746 public static final int FLAG_SUPPORTS_IS_CHILD = 1 << 4; 747 748 /** 749 * Flag indicating that this root can be ejected. 750 * 751 * @see #COLUMN_FLAGS 752 * @see DocumentsContract#ejectRoot(ContentResolver, Uri) 753 * @see DocumentsProvider#ejectRoot(String) 754 */ 755 public static final int FLAG_SUPPORTS_EJECT = 1 << 5; 756 757 /** 758 * Flag indicating that this root is currently empty. This may be used 759 * to hide the root when opening documents, but the root will still be 760 * shown when creating documents and {@link #FLAG_SUPPORTS_CREATE} is 761 * also set. If the value of this flag changes, such as when a root 762 * becomes non-empty, you must send a content changed notification for 763 * {@link DocumentsContract#buildRootsUri(String)}. 764 * 765 * @see #COLUMN_FLAGS 766 * @see ContentResolver#notifyChange(Uri, 767 * android.database.ContentObserver, boolean) 768 */ 769 public static final int FLAG_EMPTY = 1 << 6; 770 771 /** 772 * Flag indicating that this root should only be visible to advanced 773 * users. 774 * 775 * @see #COLUMN_FLAGS 776 * {@hide} 777 */ 778 @SystemApi 779 public static final int FLAG_ADVANCED = 1 << 16; 780 781 /** 782 * Flag indicating that this root has settings. 783 * 784 * @see #COLUMN_FLAGS 785 * @see DocumentsContract#ACTION_DOCUMENT_ROOT_SETTINGS 786 * {@hide} 787 */ 788 @SystemApi 789 public static final int FLAG_HAS_SETTINGS = 1 << 17; 790 791 /** 792 * Flag indicating that this root is on removable SD card storage. 793 * 794 * @see #COLUMN_FLAGS 795 * {@hide} 796 */ 797 @SystemApi 798 public static final int FLAG_REMOVABLE_SD = 1 << 18; 799 800 /** 801 * Flag indicating that this root is on removable USB storage. 802 * 803 * @see #COLUMN_FLAGS 804 * {@hide} 805 */ 806 @SystemApi 807 public static final int FLAG_REMOVABLE_USB = 1 << 19; 808 } 809 810 /** 811 * Optional boolean flag included in a directory {@link Cursor#getExtras()} 812 * indicating that a document provider is still loading data. For example, a 813 * provider has returned some results, but is still waiting on an 814 * outstanding network request. The provider must send a content changed 815 * notification when loading is finished. 816 * 817 * @see ContentResolver#notifyChange(Uri, android.database.ContentObserver, 818 * boolean) 819 */ 820 public static final String EXTRA_LOADING = "loading"; 821 822 /** 823 * Optional string included in a directory {@link Cursor#getExtras()} 824 * providing an informational message that should be shown to a user. For 825 * example, a provider may wish to indicate that not all documents are 826 * available. 827 */ 828 public static final String EXTRA_INFO = "info"; 829 830 /** 831 * Optional string included in a directory {@link Cursor#getExtras()} 832 * providing an error message that should be shown to a user. For example, a 833 * provider may wish to indicate that a network error occurred. The user may 834 * choose to retry, resulting in a new query. 835 */ 836 public static final String EXTRA_ERROR = "error"; 837 838 /** 839 * Optional result (I'm thinking boolean) answer to a question. 840 * {@hide} 841 */ 842 public static final String EXTRA_RESULT = "result"; 843 844 /** {@hide} */ 845 @UnsupportedAppUsage 846 public static final String METHOD_CREATE_DOCUMENT = "android:createDocument"; 847 /** {@hide} */ 848 public static final String METHOD_RENAME_DOCUMENT = "android:renameDocument"; 849 /** {@hide} */ 850 public static final String METHOD_DELETE_DOCUMENT = "android:deleteDocument"; 851 /** {@hide} */ 852 public static final String METHOD_COPY_DOCUMENT = "android:copyDocument"; 853 /** {@hide} */ 854 public static final String METHOD_MOVE_DOCUMENT = "android:moveDocument"; 855 /** {@hide} */ 856 public static final String METHOD_IS_CHILD_DOCUMENT = "android:isChildDocument"; 857 /** {@hide} */ 858 public static final String METHOD_REMOVE_DOCUMENT = "android:removeDocument"; 859 /** {@hide} */ 860 public static final String METHOD_EJECT_ROOT = "android:ejectRoot"; 861 /** {@hide} */ 862 public static final String METHOD_FIND_DOCUMENT_PATH = "android:findDocumentPath"; 863 /** {@hide} */ 864 public static final String METHOD_CREATE_WEB_LINK_INTENT = "android:createWebLinkIntent"; 865 /** {@hide} */ 866 public static final String METHOD_GET_DOCUMENT_METADATA = "android:getDocumentMetadata"; 867 868 /** {@hide} */ 869 public static final String EXTRA_PARENT_URI = "parentUri"; 870 /** {@hide} */ 871 public static final String EXTRA_URI = "uri"; 872 /** {@hide} */ 873 public static final String EXTRA_URI_PERMISSIONS = "uriPermissions"; 874 875 /** {@hide} */ 876 public static final String EXTRA_OPTIONS = "options"; 877 878 private static final String PATH_ROOT = "root"; 879 private static final String PATH_RECENT = "recent"; 880 @UnsupportedAppUsage 881 private static final String PATH_DOCUMENT = "document"; 882 private static final String PATH_CHILDREN = "children"; 883 private static final String PATH_SEARCH = "search"; 884 @UnsupportedAppUsage 885 private static final String PATH_TREE = "tree"; 886 887 private static final String PARAM_QUERY = "query"; 888 private static final String PARAM_MANAGE = "manage"; 889 890 /** 891 * Build URI representing the roots of a document provider. When queried, a 892 * provider will return one or more rows with columns defined by 893 * {@link Root}. 894 * 895 * @see DocumentsProvider#queryRoots(String[]) 896 */ buildRootsUri(String authority)897 public static Uri buildRootsUri(String authority) { 898 return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) 899 .authority(authority).appendPath(PATH_ROOT).build(); 900 } 901 902 /** 903 * Build URI representing the given {@link Root#COLUMN_ROOT_ID} in a 904 * document provider. 905 * 906 * @see #getRootId(Uri) 907 */ buildRootUri(String authority, String rootId)908 public static Uri buildRootUri(String authority, String rootId) { 909 return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) 910 .authority(authority).appendPath(PATH_ROOT).appendPath(rootId).build(); 911 } 912 913 /** 914 * Build URI representing the recently modified documents of a specific root 915 * in a document provider. When queried, a provider will return zero or more 916 * rows with columns defined by {@link Document}. 917 * 918 * @see DocumentsProvider#queryRecentDocuments(String, String[]) 919 * @see #getRootId(Uri) 920 */ buildRecentDocumentsUri(String authority, String rootId)921 public static Uri buildRecentDocumentsUri(String authority, String rootId) { 922 return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) 923 .authority(authority).appendPath(PATH_ROOT).appendPath(rootId) 924 .appendPath(PATH_RECENT).build(); 925 } 926 927 /** 928 * Build URI representing access to descendant documents of the given 929 * {@link Document#COLUMN_DOCUMENT_ID}. 930 * 931 * @see #getTreeDocumentId(Uri) 932 */ buildTreeDocumentUri(String authority, String documentId)933 public static Uri buildTreeDocumentUri(String authority, String documentId) { 934 return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority(authority) 935 .appendPath(PATH_TREE).appendPath(documentId).build(); 936 } 937 938 /** 939 * Build URI representing the target {@link Document#COLUMN_DOCUMENT_ID} in 940 * a document provider. When queried, a provider will return a single row 941 * with columns defined by {@link Document}. 942 * 943 * @see DocumentsProvider#queryDocument(String, String[]) 944 * @see #getDocumentId(Uri) 945 */ buildDocumentUri(String authority, String documentId)946 public static Uri buildDocumentUri(String authority, String documentId) { 947 return getBaseDocumentUriBuilder(authority).appendPath(documentId).build(); 948 } 949 950 /** 951 * Builds URI as described in {@link #buildDocumentUri(String, String)}, but such that it will 952 * be associated with the given user. 953 * 954 * @hide 955 */ 956 @SystemApi 957 @NonNull buildDocumentUriAsUser( @onNull String authority, @NonNull String documentId, @NonNull UserHandle user)958 public static Uri buildDocumentUriAsUser( 959 @NonNull String authority, @NonNull String documentId, @NonNull UserHandle user) { 960 return ContentProvider.maybeAddUserId( 961 buildDocumentUri(authority, documentId), user.getIdentifier()); 962 } 963 964 /** {@hide} */ buildBaseDocumentUri(String authority)965 public static Uri buildBaseDocumentUri(String authority) { 966 return getBaseDocumentUriBuilder(authority).build(); 967 } 968 getBaseDocumentUriBuilder(String authority)969 private static Uri.Builder getBaseDocumentUriBuilder(String authority) { 970 return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) 971 .authority(authority).appendPath(PATH_DOCUMENT); 972 } 973 974 /** 975 * Build URI representing the target {@link Document#COLUMN_DOCUMENT_ID} in 976 * a document provider. When queried, a provider will return a single row 977 * with columns defined by {@link Document}. 978 * <p> 979 * However, instead of directly accessing the target document, the returned 980 * URI will leverage access granted through a subtree URI, typically 981 * returned by {@link Intent#ACTION_OPEN_DOCUMENT_TREE}. The target document 982 * must be a descendant (child, grandchild, etc) of the subtree. 983 * <p> 984 * This is typically used to access documents under a user-selected 985 * directory tree, since it doesn't require the user to separately confirm 986 * each new document access. 987 * 988 * @param treeUri the subtree to leverage to gain access to the target 989 * document. The target directory must be a descendant of this 990 * subtree. 991 * @param documentId the target document, which the caller may not have 992 * direct access to. 993 * @see Intent#ACTION_OPEN_DOCUMENT_TREE 994 * @see DocumentsProvider#isChildDocument(String, String) 995 * @see #buildDocumentUri(String, String) 996 */ buildDocumentUriUsingTree(Uri treeUri, String documentId)997 public static Uri buildDocumentUriUsingTree(Uri treeUri, String documentId) { 998 return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) 999 .authority(treeUri.getAuthority()).appendPath(PATH_TREE) 1000 .appendPath(getTreeDocumentId(treeUri)).appendPath(PATH_DOCUMENT) 1001 .appendPath(documentId).build(); 1002 } 1003 1004 /** {@hide} */ buildDocumentUriMaybeUsingTree(Uri baseUri, String documentId)1005 public static Uri buildDocumentUriMaybeUsingTree(Uri baseUri, String documentId) { 1006 if (isTreeUri(baseUri)) { 1007 return buildDocumentUriUsingTree(baseUri, documentId); 1008 } else { 1009 return buildDocumentUri(baseUri.getAuthority(), documentId); 1010 } 1011 } 1012 1013 /** 1014 * Build URI representing the children of the target directory in a document 1015 * provider. When queried, a provider will return zero or more rows with 1016 * columns defined by {@link Document}. 1017 * 1018 * @param parentDocumentId the document to return children for, which must 1019 * be a directory with MIME type of 1020 * {@link Document#MIME_TYPE_DIR}. 1021 * @see DocumentsProvider#queryChildDocuments(String, String[], String) 1022 * @see #getDocumentId(Uri) 1023 */ buildChildDocumentsUri(String authority, String parentDocumentId)1024 public static Uri buildChildDocumentsUri(String authority, String parentDocumentId) { 1025 return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority(authority) 1026 .appendPath(PATH_DOCUMENT).appendPath(parentDocumentId).appendPath(PATH_CHILDREN) 1027 .build(); 1028 } 1029 1030 /** 1031 * Build URI representing the children of the target directory in a document 1032 * provider. When queried, a provider will return zero or more rows with 1033 * columns defined by {@link Document}. 1034 * <p> 1035 * However, instead of directly accessing the target directory, the returned 1036 * URI will leverage access granted through a subtree URI, typically 1037 * returned by {@link Intent#ACTION_OPEN_DOCUMENT_TREE}. The target 1038 * directory must be a descendant (child, grandchild, etc) of the subtree. 1039 * <p> 1040 * This is typically used to access documents under a user-selected 1041 * directory tree, since it doesn't require the user to separately confirm 1042 * each new document access. 1043 * 1044 * @param treeUri the subtree to leverage to gain access to the target 1045 * document. The target directory must be a descendant of this 1046 * subtree. 1047 * @param parentDocumentId the document to return children for, which the 1048 * caller may not have direct access to, and which must be a 1049 * directory with MIME type of {@link Document#MIME_TYPE_DIR}. 1050 * @see Intent#ACTION_OPEN_DOCUMENT_TREE 1051 * @see DocumentsProvider#isChildDocument(String, String) 1052 * @see #buildChildDocumentsUri(String, String) 1053 */ buildChildDocumentsUriUsingTree(Uri treeUri, String parentDocumentId)1054 public static Uri buildChildDocumentsUriUsingTree(Uri treeUri, String parentDocumentId) { 1055 return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT) 1056 .authority(treeUri.getAuthority()).appendPath(PATH_TREE) 1057 .appendPath(getTreeDocumentId(treeUri)).appendPath(PATH_DOCUMENT) 1058 .appendPath(parentDocumentId).appendPath(PATH_CHILDREN).build(); 1059 } 1060 1061 /** 1062 * Build URI representing a search for matching documents under a specific 1063 * root in a document provider. When queried, a provider will return zero or 1064 * more rows with columns defined by {@link Document}. 1065 * 1066 * @see DocumentsProvider#querySearchDocuments(String, String, String[]) 1067 * @see #getRootId(Uri) 1068 * @see #getSearchDocumentsQuery(Uri) 1069 */ buildSearchDocumentsUri( String authority, String rootId, String query)1070 public static Uri buildSearchDocumentsUri( 1071 String authority, String rootId, String query) { 1072 return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority(authority) 1073 .appendPath(PATH_ROOT).appendPath(rootId).appendPath(PATH_SEARCH) 1074 .appendQueryParameter(PARAM_QUERY, query).build(); 1075 } 1076 1077 /** 1078 * Check if the values match the query arguments. 1079 * 1080 * @param queryArgs the query arguments 1081 * @param displayName the display time to check against 1082 * @param mimeType the mime type to check against 1083 * @param lastModified the last modified time to check against 1084 * @param size the size to check against 1085 * @hide 1086 */ matchSearchQueryArguments(Bundle queryArgs, String displayName, String mimeType, long lastModified, long size)1087 public static boolean matchSearchQueryArguments(Bundle queryArgs, String displayName, 1088 String mimeType, long lastModified, long size) { 1089 if (queryArgs == null) { 1090 return true; 1091 } 1092 1093 final String argDisplayName = queryArgs.getString(QUERY_ARG_DISPLAY_NAME, ""); 1094 if (!argDisplayName.isEmpty()) { 1095 // TODO (118795812) : Enhance the search string handled in DocumentsProvider 1096 if (!displayName.toLowerCase().contains(argDisplayName.toLowerCase())) { 1097 return false; 1098 } 1099 } 1100 1101 final long argFileSize = queryArgs.getLong(QUERY_ARG_FILE_SIZE_OVER, -1 /* defaultValue */); 1102 if (argFileSize != -1 && size < argFileSize) { 1103 return false; 1104 } 1105 1106 final long argLastModified = queryArgs.getLong(QUERY_ARG_LAST_MODIFIED_AFTER, 1107 -1 /* defaultValue */); 1108 if (argLastModified != -1 && lastModified < argLastModified) { 1109 return false; 1110 } 1111 1112 final String[] argMimeTypes = queryArgs.getStringArray(QUERY_ARG_MIME_TYPES); 1113 if (argMimeTypes != null && argMimeTypes.length > 0) { 1114 mimeType = Intent.normalizeMimeType(mimeType); 1115 for (String type : argMimeTypes) { 1116 if (MimeTypeFilter.matches(mimeType, Intent.normalizeMimeType(type))) { 1117 return true; 1118 } 1119 } 1120 return false; 1121 } 1122 return true; 1123 } 1124 1125 /** 1126 * Get the handled query arguments from the query bundle. The handled arguments are 1127 * {@link DocumentsContract#QUERY_ARG_EXCLUDE_MEDIA}, 1128 * {@link DocumentsContract#QUERY_ARG_DISPLAY_NAME}, 1129 * {@link DocumentsContract#QUERY_ARG_MIME_TYPES}, 1130 * {@link DocumentsContract#QUERY_ARG_FILE_SIZE_OVER} and 1131 * {@link DocumentsContract#QUERY_ARG_LAST_MODIFIED_AFTER}. 1132 * 1133 * @param queryArgs the query arguments to be parsed. 1134 * @return the handled query arguments 1135 * @hide 1136 */ getHandledQueryArguments(Bundle queryArgs)1137 public static String[] getHandledQueryArguments(Bundle queryArgs) { 1138 if (queryArgs == null) { 1139 return new String[0]; 1140 } 1141 1142 final ArrayList<String> args = new ArrayList<>(); 1143 1144 if (queryArgs.keySet().contains(QUERY_ARG_EXCLUDE_MEDIA)) { 1145 args.add(QUERY_ARG_EXCLUDE_MEDIA); 1146 } 1147 1148 if (queryArgs.keySet().contains(QUERY_ARG_DISPLAY_NAME)) { 1149 args.add(QUERY_ARG_DISPLAY_NAME); 1150 } 1151 1152 if (queryArgs.keySet().contains(QUERY_ARG_FILE_SIZE_OVER)) { 1153 args.add(QUERY_ARG_FILE_SIZE_OVER); 1154 } 1155 1156 if (queryArgs.keySet().contains(QUERY_ARG_LAST_MODIFIED_AFTER)) { 1157 args.add(QUERY_ARG_LAST_MODIFIED_AFTER); 1158 } 1159 1160 if (queryArgs.keySet().contains(QUERY_ARG_MIME_TYPES)) { 1161 args.add(QUERY_ARG_MIME_TYPES); 1162 } 1163 return args.toArray(new String[0]); 1164 } 1165 1166 /** 1167 * Test if the given URI represents a {@link Document} backed by a 1168 * {@link DocumentsProvider}. 1169 * 1170 * @see #buildDocumentUri(String, String) 1171 * @see #buildDocumentUriUsingTree(Uri, String) 1172 */ isDocumentUri(Context context, @Nullable Uri uri)1173 public static boolean isDocumentUri(Context context, @Nullable Uri uri) { 1174 if (isContentUri(uri) && isDocumentsProvider(context, uri.getAuthority())) { 1175 final List<String> paths = uri.getPathSegments(); 1176 if (paths.size() == 2) { 1177 return PATH_DOCUMENT.equals(paths.get(0)); 1178 } else if (paths.size() == 4) { 1179 return PATH_TREE.equals(paths.get(0)) && PATH_DOCUMENT.equals(paths.get(2)); 1180 } 1181 } 1182 return false; 1183 } 1184 1185 /** 1186 * Test if the given URI represents all roots of the authority 1187 * backed by {@link DocumentsProvider}. 1188 * 1189 * @see #buildRootsUri(String) 1190 */ isRootsUri(@onNull Context context, @Nullable Uri uri)1191 public static boolean isRootsUri(@NonNull Context context, @Nullable Uri uri) { 1192 Preconditions.checkNotNull(context, "context can not be null"); 1193 return isRootUri(context, uri, 1 /* pathSize */); 1194 } 1195 1196 /** 1197 * Test if the given URI represents specific root backed by {@link DocumentsProvider}. 1198 * 1199 * @see #buildRootUri(String, String) 1200 */ isRootUri(@onNull Context context, @Nullable Uri uri)1201 public static boolean isRootUri(@NonNull Context context, @Nullable Uri uri) { 1202 Preconditions.checkNotNull(context, "context can not be null"); 1203 return isRootUri(context, uri, 2 /* pathSize */); 1204 } 1205 1206 /** {@hide} */ isContentUri(@ullable Uri uri)1207 public static boolean isContentUri(@Nullable Uri uri) { 1208 return uri != null && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme()); 1209 } 1210 1211 /** 1212 * Test if the given URI represents a {@link Document} tree. 1213 * 1214 * @see #buildTreeDocumentUri(String, String) 1215 * @see #getTreeDocumentId(Uri) 1216 */ isTreeUri(Uri uri)1217 public static boolean isTreeUri(Uri uri) { 1218 final List<String> paths = uri.getPathSegments(); 1219 return (paths.size() >= 2 && PATH_TREE.equals(paths.get(0))); 1220 } 1221 isRootUri(Context context, @Nullable Uri uri, int pathSize)1222 private static boolean isRootUri(Context context, @Nullable Uri uri, int pathSize) { 1223 if (isContentUri(uri) && isDocumentsProvider(context, uri.getAuthority())) { 1224 final List<String> paths = uri.getPathSegments(); 1225 return (paths.size() == pathSize && PATH_ROOT.equals(paths.get(0))); 1226 } 1227 return false; 1228 } 1229 isDocumentsProvider(Context context, String authority)1230 private static boolean isDocumentsProvider(Context context, String authority) { 1231 final Intent intent = new Intent(PROVIDER_INTERFACE); 1232 final List<ResolveInfo> infos = context.getPackageManager() 1233 .queryIntentContentProviders(intent, 0); 1234 for (ResolveInfo info : infos) { 1235 if (authority.equals(info.providerInfo.authority)) { 1236 return true; 1237 } 1238 } 1239 return false; 1240 } 1241 1242 /** 1243 * Extract the {@link Root#COLUMN_ROOT_ID} from the given URI. 1244 */ getRootId(Uri rootUri)1245 public static String getRootId(Uri rootUri) { 1246 final List<String> paths = rootUri.getPathSegments(); 1247 if (paths.size() >= 2 && PATH_ROOT.equals(paths.get(0))) { 1248 return paths.get(1); 1249 } 1250 throw new IllegalArgumentException("Invalid URI: " + rootUri); 1251 } 1252 1253 /** 1254 * Extract the {@link Document#COLUMN_DOCUMENT_ID} from the given URI. 1255 * 1256 * @see #isDocumentUri(Context, Uri) 1257 */ getDocumentId(Uri documentUri)1258 public static String getDocumentId(Uri documentUri) { 1259 final List<String> paths = documentUri.getPathSegments(); 1260 if (paths.size() >= 2 && PATH_DOCUMENT.equals(paths.get(0))) { 1261 return paths.get(1); 1262 } 1263 if (paths.size() >= 4 && PATH_TREE.equals(paths.get(0)) 1264 && PATH_DOCUMENT.equals(paths.get(2))) { 1265 return paths.get(3); 1266 } 1267 throw new IllegalArgumentException("Invalid URI: " + documentUri); 1268 } 1269 1270 /** 1271 * Extract the via {@link Document#COLUMN_DOCUMENT_ID} from the given URI. 1272 */ getTreeDocumentId(Uri documentUri)1273 public static String getTreeDocumentId(Uri documentUri) { 1274 final List<String> paths = documentUri.getPathSegments(); 1275 if (paths.size() >= 2 && PATH_TREE.equals(paths.get(0))) { 1276 return paths.get(1); 1277 } 1278 throw new IllegalArgumentException("Invalid URI: " + documentUri); 1279 } 1280 1281 /** 1282 * Extract the search query from a URI built by 1283 * {@link #buildSearchDocumentsUri(String, String, String)}. 1284 */ getSearchDocumentsQuery(Uri searchDocumentsUri)1285 public static String getSearchDocumentsQuery(Uri searchDocumentsUri) { 1286 return searchDocumentsUri.getQueryParameter(PARAM_QUERY); 1287 } 1288 1289 /** 1290 * Extract the search query from a Bundle 1291 * {@link #QUERY_ARG_DISPLAY_NAME}. 1292 * {@hide} 1293 */ getSearchDocumentsQuery(@onNull Bundle bundle)1294 public static String getSearchDocumentsQuery(@NonNull Bundle bundle) { 1295 Preconditions.checkNotNull(bundle, "bundle can not be null"); 1296 return bundle.getString(QUERY_ARG_DISPLAY_NAME, "" /* defaultValue */); 1297 } 1298 1299 /** 1300 * Build URI that append the query parameter {@link PARAM_MANAGE} to 1301 * enable the manage mode. 1302 * @see DocumentsProvider#queryChildDocumentsForManage(String parentDocId, String[], String) 1303 * {@hide} 1304 */ 1305 @SystemApi 1306 @TestApi setManageMode(@onNull Uri uri)1307 public static @NonNull Uri setManageMode(@NonNull Uri uri) { 1308 Preconditions.checkNotNull(uri, "uri can not be null"); 1309 return uri.buildUpon().appendQueryParameter(PARAM_MANAGE, "true").build(); 1310 } 1311 1312 /** 1313 * Extract the manage mode from a URI built by 1314 * {@link #setManageMode(Uri)}. 1315 * {@hide} 1316 */ 1317 @SystemApi 1318 @TestApi isManageMode(@onNull Uri uri)1319 public static boolean isManageMode(@NonNull Uri uri) { 1320 Preconditions.checkNotNull(uri, "uri can not be null"); 1321 return uri.getBooleanQueryParameter(PARAM_MANAGE, false); 1322 } 1323 1324 /** 1325 * Return thumbnail representing the document at the given URI. Callers are 1326 * responsible for their own in-memory caching. 1327 * 1328 * @param documentUri document to return thumbnail for, which must have 1329 * {@link Document#FLAG_SUPPORTS_THUMBNAIL} set. 1330 * @param size optimal thumbnail size desired. A provider may return a 1331 * thumbnail of a different size, but never more than double the 1332 * requested size. 1333 * @param signal signal used to indicate if caller is no longer interested 1334 * in the thumbnail. 1335 * @return decoded thumbnail, or {@code null} if problem was encountered. 1336 * @see DocumentsProvider#openDocumentThumbnail(String, Point, 1337 * android.os.CancellationSignal) 1338 */ getDocumentThumbnail(@onNull ContentResolver content, @NonNull Uri documentUri, @NonNull Point size, @Nullable CancellationSignal signal)1339 public static @Nullable Bitmap getDocumentThumbnail(@NonNull ContentResolver content, 1340 @NonNull Uri documentUri, @NonNull Point size, @Nullable CancellationSignal signal) 1341 throws FileNotFoundException { 1342 try { 1343 return ContentResolver.loadThumbnail(content, documentUri, Point.convert(size), signal, 1344 ImageDecoder.ALLOCATOR_SOFTWARE); 1345 } catch (Exception e) { 1346 if (!(e instanceof OperationCanceledException)) { 1347 Log.w(TAG, "Failed to load thumbnail for " + documentUri + ": " + e); 1348 } 1349 rethrowIfNecessary(e); 1350 return null; 1351 } 1352 } 1353 1354 /** 1355 * Create a new document with given MIME type and display name. 1356 * 1357 * @param parentDocumentUri directory with {@link Document#FLAG_DIR_SUPPORTS_CREATE} 1358 * @param mimeType MIME type of new document 1359 * @param displayName name of new document 1360 * @return newly created document, or {@code null} if failed 1361 */ createDocument(@onNull ContentResolver content, @NonNull Uri parentDocumentUri, @NonNull String mimeType, @NonNull String displayName)1362 public static @Nullable Uri createDocument(@NonNull ContentResolver content, 1363 @NonNull Uri parentDocumentUri, @NonNull String mimeType, @NonNull String displayName) 1364 throws FileNotFoundException { 1365 try { 1366 final Bundle in = new Bundle(); 1367 in.putParcelable(DocumentsContract.EXTRA_URI, parentDocumentUri); 1368 in.putString(Document.COLUMN_MIME_TYPE, mimeType); 1369 in.putString(Document.COLUMN_DISPLAY_NAME, displayName); 1370 1371 final Bundle out = content.call(parentDocumentUri.getAuthority(), 1372 METHOD_CREATE_DOCUMENT, null, in); 1373 return out.getParcelable(DocumentsContract.EXTRA_URI); 1374 } catch (Exception e) { 1375 Log.w(TAG, "Failed to create document", e); 1376 rethrowIfNecessary(e); 1377 return null; 1378 } 1379 } 1380 1381 /** 1382 * Test if a document is descendant (child, grandchild, etc) from the given 1383 * parent. 1384 * 1385 * @param parentDocumentUri parent to verify against. 1386 * @param childDocumentUri child to verify. 1387 * @return if given document is a descendant of the given parent. 1388 * @see Root#FLAG_SUPPORTS_IS_CHILD 1389 */ isChildDocument(@onNull ContentResolver content, @NonNull Uri parentDocumentUri, @NonNull Uri childDocumentUri)1390 public static boolean isChildDocument(@NonNull ContentResolver content, 1391 @NonNull Uri parentDocumentUri, @NonNull Uri childDocumentUri) 1392 throws FileNotFoundException { 1393 Preconditions.checkNotNull(content, "content can not be null"); 1394 Preconditions.checkNotNull(parentDocumentUri, "parentDocumentUri can not be null"); 1395 Preconditions.checkNotNull(childDocumentUri, "childDocumentUri can not be null"); 1396 try { 1397 final Bundle in = new Bundle(); 1398 in.putParcelable(DocumentsContract.EXTRA_URI, parentDocumentUri); 1399 in.putParcelable(DocumentsContract.EXTRA_TARGET_URI, childDocumentUri); 1400 1401 final Bundle out = content.call(parentDocumentUri.getAuthority(), 1402 METHOD_IS_CHILD_DOCUMENT, null, in); 1403 if (out == null) { 1404 throw new RemoteException("Failed to get a response from isChildDocument query."); 1405 } 1406 if (!out.containsKey(DocumentsContract.EXTRA_RESULT)) { 1407 throw new RemoteException("Response did not include result field.."); 1408 } 1409 return out.getBoolean(DocumentsContract.EXTRA_RESULT); 1410 } catch (Exception e) { 1411 Log.w(TAG, "Failed to create document", e); 1412 rethrowIfNecessary(e); 1413 return false; 1414 } 1415 } 1416 1417 /** 1418 * Change the display name of an existing document. 1419 * <p> 1420 * If the underlying provider needs to create a new 1421 * {@link Document#COLUMN_DOCUMENT_ID} to represent the updated display 1422 * name, that new document is returned and the original document is no 1423 * longer valid. Otherwise, the original document is returned. 1424 * 1425 * @param documentUri document with {@link Document#FLAG_SUPPORTS_RENAME} 1426 * @param displayName updated name for document 1427 * @return the existing or new document after the rename, or {@code null} if 1428 * failed. 1429 */ renameDocument(@onNull ContentResolver content, @NonNull Uri documentUri, @NonNull String displayName)1430 public static @Nullable Uri renameDocument(@NonNull ContentResolver content, 1431 @NonNull Uri documentUri, @NonNull String displayName) throws FileNotFoundException { 1432 try { 1433 final Bundle in = new Bundle(); 1434 in.putParcelable(DocumentsContract.EXTRA_URI, documentUri); 1435 in.putString(Document.COLUMN_DISPLAY_NAME, displayName); 1436 1437 final Bundle out = content.call(documentUri.getAuthority(), 1438 METHOD_RENAME_DOCUMENT, null, in); 1439 final Uri outUri = out.getParcelable(DocumentsContract.EXTRA_URI); 1440 return (outUri != null) ? outUri : documentUri; 1441 } catch (Exception e) { 1442 Log.w(TAG, "Failed to rename document", e); 1443 rethrowIfNecessary(e); 1444 return null; 1445 } 1446 } 1447 1448 /** 1449 * Delete the given document. 1450 * 1451 * @param documentUri document with {@link Document#FLAG_SUPPORTS_DELETE} 1452 * @return if the document was deleted successfully. 1453 */ deleteDocument(@onNull ContentResolver content, @NonNull Uri documentUri)1454 public static boolean deleteDocument(@NonNull ContentResolver content, @NonNull Uri documentUri) 1455 throws FileNotFoundException { 1456 try { 1457 final Bundle in = new Bundle(); 1458 in.putParcelable(DocumentsContract.EXTRA_URI, documentUri); 1459 1460 content.call(documentUri.getAuthority(), 1461 METHOD_DELETE_DOCUMENT, null, in); 1462 return true; 1463 } catch (Exception e) { 1464 Log.w(TAG, "Failed to delete document", e); 1465 rethrowIfNecessary(e); 1466 return false; 1467 } 1468 } 1469 1470 /** 1471 * Copies the given document. 1472 * 1473 * @param sourceDocumentUri document with {@link Document#FLAG_SUPPORTS_COPY} 1474 * @param targetParentDocumentUri document which will become a parent of the source 1475 * document's copy. 1476 * @return the copied document, or {@code null} if failed. 1477 */ copyDocument(@onNull ContentResolver content, @NonNull Uri sourceDocumentUri, @NonNull Uri targetParentDocumentUri)1478 public static @Nullable Uri copyDocument(@NonNull ContentResolver content, 1479 @NonNull Uri sourceDocumentUri, @NonNull Uri targetParentDocumentUri) 1480 throws FileNotFoundException { 1481 try { 1482 final Bundle in = new Bundle(); 1483 in.putParcelable(DocumentsContract.EXTRA_URI, sourceDocumentUri); 1484 in.putParcelable(DocumentsContract.EXTRA_TARGET_URI, targetParentDocumentUri); 1485 1486 final Bundle out = content.call(sourceDocumentUri.getAuthority(), 1487 METHOD_COPY_DOCUMENT, null, in); 1488 return out.getParcelable(DocumentsContract.EXTRA_URI); 1489 } catch (Exception e) { 1490 Log.w(TAG, "Failed to copy document", e); 1491 rethrowIfNecessary(e); 1492 return null; 1493 } 1494 } 1495 1496 /** 1497 * Moves the given document under a new parent. 1498 * 1499 * @param sourceDocumentUri document with {@link Document#FLAG_SUPPORTS_MOVE} 1500 * @param sourceParentDocumentUri parent document of the document to move. 1501 * @param targetParentDocumentUri document which will become a new parent of the source 1502 * document. 1503 * @return the moved document, or {@code null} if failed. 1504 */ moveDocument(@onNull ContentResolver content, @NonNull Uri sourceDocumentUri, @NonNull Uri sourceParentDocumentUri, @NonNull Uri targetParentDocumentUri)1505 public static @Nullable Uri moveDocument(@NonNull ContentResolver content, 1506 @NonNull Uri sourceDocumentUri, @NonNull Uri sourceParentDocumentUri, 1507 @NonNull Uri targetParentDocumentUri) throws FileNotFoundException { 1508 try { 1509 final Bundle in = new Bundle(); 1510 in.putParcelable(DocumentsContract.EXTRA_URI, sourceDocumentUri); 1511 in.putParcelable(DocumentsContract.EXTRA_PARENT_URI, sourceParentDocumentUri); 1512 in.putParcelable(DocumentsContract.EXTRA_TARGET_URI, targetParentDocumentUri); 1513 1514 final Bundle out = content.call(sourceDocumentUri.getAuthority(), 1515 METHOD_MOVE_DOCUMENT, null, in); 1516 return out.getParcelable(DocumentsContract.EXTRA_URI); 1517 } catch (Exception e) { 1518 Log.w(TAG, "Failed to move document", e); 1519 rethrowIfNecessary(e); 1520 return null; 1521 } 1522 } 1523 1524 /** 1525 * Removes the given document from a parent directory. 1526 * 1527 * <p>In contrast to {@link #deleteDocument} it requires specifying the parent. 1528 * This method is especially useful if the document can be in multiple parents. 1529 * 1530 * @param documentUri document with {@link Document#FLAG_SUPPORTS_REMOVE} 1531 * @param parentDocumentUri parent document of the document to remove. 1532 * @return true if the document was removed successfully. 1533 */ removeDocument(@onNull ContentResolver content, @NonNull Uri documentUri, @NonNull Uri parentDocumentUri)1534 public static boolean removeDocument(@NonNull ContentResolver content, @NonNull Uri documentUri, 1535 @NonNull Uri parentDocumentUri) throws FileNotFoundException { 1536 try { 1537 final Bundle in = new Bundle(); 1538 in.putParcelable(DocumentsContract.EXTRA_URI, documentUri); 1539 in.putParcelable(DocumentsContract.EXTRA_PARENT_URI, parentDocumentUri); 1540 1541 content.call(documentUri.getAuthority(), 1542 METHOD_REMOVE_DOCUMENT, null, in); 1543 return true; 1544 } catch (Exception e) { 1545 Log.w(TAG, "Failed to remove document", e); 1546 rethrowIfNecessary(e); 1547 return false; 1548 } 1549 } 1550 1551 /** 1552 * Ejects the given root. It throws {@link IllegalStateException} when ejection failed. 1553 * 1554 * @param rootUri root with {@link Root#FLAG_SUPPORTS_EJECT} to be ejected 1555 */ ejectRoot(@onNull ContentResolver content, @NonNull Uri rootUri)1556 public static void ejectRoot(@NonNull ContentResolver content, @NonNull Uri rootUri) { 1557 try { 1558 final Bundle in = new Bundle(); 1559 in.putParcelable(DocumentsContract.EXTRA_URI, rootUri); 1560 1561 content.call(rootUri.getAuthority(), 1562 METHOD_EJECT_ROOT, null, in); 1563 } catch (Exception e) { 1564 Log.w(TAG, "Failed to eject", e); 1565 } 1566 } 1567 1568 /** 1569 * Returns metadata associated with the document. The type of metadata returned 1570 * is specific to the document type. For example the data returned for an image 1571 * file will likely consist primarily or solely of EXIF metadata. 1572 * 1573 * <p>The returned {@link Bundle} will contain zero or more entries depending 1574 * on the type of data supported by the document provider. 1575 * 1576 * <ol> 1577 * <li>A {@link DocumentsContract#METADATA_TYPES} containing a {@code String[]} value. 1578 * The string array identifies the type or types of metadata returned. Each 1579 * value in the can be used to access a {@link Bundle} of data 1580 * containing that type of data. 1581 * <li>An entry each for each type of returned metadata. Each set of metadata is 1582 * itself represented as a bundle and accessible via a string key naming 1583 * the type of data. 1584 * </ol> 1585 * 1586 * <p>Example: 1587 * <p><pre><code> 1588 * Bundle metadata = DocumentsContract.getDocumentMetadata(client, imageDocUri, tags); 1589 * if (metadata.containsKey(DocumentsContract.METADATA_EXIF)) { 1590 * Bundle exif = metadata.getBundle(DocumentsContract.METADATA_EXIF); 1591 * int imageLength = exif.getInt(ExifInterface.TAG_IMAGE_LENGTH); 1592 * } 1593 * </code></pre> 1594 * 1595 * @param documentUri a Document URI 1596 * @return a Bundle of Bundles. 1597 */ getDocumentMetadata(@onNull ContentResolver content, @NonNull Uri documentUri)1598 public static @Nullable Bundle getDocumentMetadata(@NonNull ContentResolver content, 1599 @NonNull Uri documentUri) throws FileNotFoundException { 1600 Preconditions.checkNotNull(content, "content can not be null"); 1601 Preconditions.checkNotNull(documentUri, "documentUri can not be null"); 1602 try { 1603 final Bundle in = new Bundle(); 1604 in.putParcelable(EXTRA_URI, documentUri); 1605 1606 return content.call(documentUri.getAuthority(), 1607 METHOD_GET_DOCUMENT_METADATA, null, in); 1608 } catch (Exception e) { 1609 Log.w(TAG, "Failed to get document metadata"); 1610 rethrowIfNecessary(e); 1611 return null; 1612 } 1613 } 1614 1615 /** 1616 * Finds the canonical path from the top of the document tree. 1617 * 1618 * The {@link Path#getPath()} of the return value contains the document ID 1619 * of all documents along the path from the top the document tree to the 1620 * requested document, both inclusive. 1621 * 1622 * The {@link Path#getRootId()} of the return value returns {@code null}. 1623 * 1624 * @param treeUri treeUri of the document which path is requested. 1625 * @return the path of the document, or {@code null} if failed. 1626 * @see DocumentsProvider#findDocumentPath(String, String) 1627 */ findDocumentPath(@onNull ContentResolver content, @NonNull Uri treeUri)1628 public static @Nullable Path findDocumentPath(@NonNull ContentResolver content, 1629 @NonNull Uri treeUri) throws FileNotFoundException { 1630 try { 1631 final Bundle in = new Bundle(); 1632 in.putParcelable(DocumentsContract.EXTRA_URI, treeUri); 1633 1634 final Bundle out = content.call(treeUri.getAuthority(), 1635 METHOD_FIND_DOCUMENT_PATH, null, in); 1636 return out.getParcelable(DocumentsContract.EXTRA_RESULT); 1637 } catch (Exception e) { 1638 Log.w(TAG, "Failed to find path", e); 1639 rethrowIfNecessary(e); 1640 return null; 1641 } 1642 } 1643 1644 /** 1645 * Creates an intent for obtaining a web link for the specified document. 1646 * 1647 * <p>Note, that due to internal limitations, if there is already a web link 1648 * intent created for the specified document but with different options, 1649 * then it may be overridden. 1650 * 1651 * <p>Providers are required to show confirmation UI for all new permissions granted 1652 * for the linked document. 1653 * 1654 * <p>If list of recipients is known, then it should be passed in options as 1655 * {@link Intent#EXTRA_EMAIL} as a list of email addresses. Note, that 1656 * this is just a hint for the provider, which can ignore the list. In either 1657 * case the provider is required to show a UI for letting the user confirm 1658 * any new permission grants. 1659 * 1660 * <p>Note, that the entire <code>options</code> bundle will be sent to the provider 1661 * backing the passed <code>uri</code>. Make sure that you trust the provider 1662 * before passing any sensitive information. 1663 * 1664 * <p>Since this API may show a UI, it cannot be called from background. 1665 * 1666 * <p>In order to obtain the Web Link use code like this: 1667 * <pre><code> 1668 * void onSomethingHappened() { 1669 * IntentSender sender = DocumentsContract.createWebLinkIntent(<i>...</i>); 1670 * if (sender != null) { 1671 * startIntentSenderForResult( 1672 * sender, 1673 * WEB_LINK_REQUEST_CODE, 1674 * null, 0, 0, 0, null); 1675 * } 1676 * } 1677 * 1678 * <i>(...)</i> 1679 * 1680 * void onActivityResult(int requestCode, int resultCode, Intent data) { 1681 * if (requestCode == WEB_LINK_REQUEST_CODE && resultCode == RESULT_OK) { 1682 * Uri weblinkUri = data.getData(); 1683 * <i>...</i> 1684 * } 1685 * } 1686 * </code></pre> 1687 * 1688 * @param uri uri for the document to create a link to. 1689 * @param options Extra information for generating the link. 1690 * @return an intent sender to obtain the web link, or null if the document 1691 * is not linkable, or creating the intent sender failed. 1692 * @see DocumentsProvider#createWebLinkIntent(String, Bundle) 1693 * @see Intent#EXTRA_EMAIL 1694 */ createWebLinkIntent(@onNull ContentResolver content, @NonNull Uri uri, @Nullable Bundle options)1695 public static @Nullable IntentSender createWebLinkIntent(@NonNull ContentResolver content, 1696 @NonNull Uri uri, @Nullable Bundle options) throws FileNotFoundException { 1697 try { 1698 final Bundle in = new Bundle(); 1699 in.putParcelable(DocumentsContract.EXTRA_URI, uri); 1700 1701 // Options may be provider specific, so put them in a separate bundle to 1702 // avoid overriding the Uri. 1703 if (options != null) { 1704 in.putBundle(EXTRA_OPTIONS, options); 1705 } 1706 1707 final Bundle out = content.call(uri.getAuthority(), 1708 METHOD_CREATE_WEB_LINK_INTENT, null, in); 1709 return out.getParcelable(DocumentsContract.EXTRA_RESULT); 1710 } catch (Exception e) { 1711 Log.w(TAG, "Failed to create a web link intent", e); 1712 rethrowIfNecessary(e); 1713 return null; 1714 } 1715 } 1716 1717 /** 1718 * Open the given image for thumbnail purposes, using any embedded EXIF 1719 * thumbnail if available, and providing orientation hints from the parent 1720 * image. 1721 * 1722 * @hide 1723 */ openImageThumbnail(File file)1724 public static AssetFileDescriptor openImageThumbnail(File file) throws FileNotFoundException { 1725 final ParcelFileDescriptor pfd = ParcelFileDescriptor.open( 1726 file, ParcelFileDescriptor.MODE_READ_ONLY); 1727 try { 1728 final ExifInterface exif = new ExifInterface(file.getAbsolutePath()); 1729 1730 final long[] thumb = exif.getThumbnailRange(); 1731 if (thumb != null) { 1732 // If we use thumb to decode, we need to handle the rotation by ourselves. 1733 Bundle extras = null; 1734 switch (exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1)) { 1735 case ExifInterface.ORIENTATION_ROTATE_90: 1736 extras = new Bundle(1); 1737 extras.putInt(EXTRA_ORIENTATION, 90); 1738 break; 1739 case ExifInterface.ORIENTATION_ROTATE_180: 1740 extras = new Bundle(1); 1741 extras.putInt(EXTRA_ORIENTATION, 180); 1742 break; 1743 case ExifInterface.ORIENTATION_ROTATE_270: 1744 extras = new Bundle(1); 1745 extras.putInt(EXTRA_ORIENTATION, 270); 1746 break; 1747 } 1748 1749 return new AssetFileDescriptor(pfd, thumb[0], thumb[1], extras); 1750 } 1751 } catch (IOException e) { 1752 } 1753 1754 // Do full file decoding, we don't need to handle the orientation 1755 return new AssetFileDescriptor(pfd, 0, AssetFileDescriptor.UNKNOWN_LENGTH, null); 1756 } 1757 rethrowIfNecessary(Exception e)1758 private static void rethrowIfNecessary(Exception e) throws FileNotFoundException { 1759 // We only want to throw applications targetting O and above 1760 if (VMRuntime.getRuntime().getTargetSdkVersion() >= Build.VERSION_CODES.O) { 1761 if (e instanceof ParcelableException) { 1762 ((ParcelableException) e).maybeRethrow(FileNotFoundException.class); 1763 } else if (e instanceof RemoteException) { 1764 ((RemoteException) e).rethrowAsRuntimeException(); 1765 } else if (e instanceof RuntimeException) { 1766 throw (RuntimeException) e; 1767 } 1768 } 1769 } 1770 1771 /** 1772 * Holds a path from a document to a particular document under it. It 1773 * may also contains the root ID where the path resides. 1774 */ 1775 public static final class Path implements Parcelable { 1776 1777 private final @Nullable String mRootId; 1778 private final List<String> mPath; 1779 1780 /** 1781 * Creates a Path. 1782 * 1783 * @param rootId the ID of the root. May be null. 1784 * @param path the list of document ID from the parent document at 1785 * position 0 to the child document. 1786 */ Path(@ullable String rootId, List<String> path)1787 public Path(@Nullable String rootId, List<String> path) { 1788 checkCollectionNotEmpty(path, "path"); 1789 checkCollectionElementsNotNull(path, "path"); 1790 1791 mRootId = rootId; 1792 mPath = path; 1793 } 1794 1795 /** 1796 * Returns the root id or null if the calling package doesn't have 1797 * permission to access root information. 1798 */ getRootId()1799 public @Nullable String getRootId() { 1800 return mRootId; 1801 } 1802 1803 /** 1804 * Returns the path. The path is trimmed to the top of tree if 1805 * calling package doesn't have permission to access those 1806 * documents. 1807 */ getPath()1808 public List<String> getPath() { 1809 return mPath; 1810 } 1811 1812 @Override equals(Object o)1813 public boolean equals(Object o) { 1814 if (this == o) { 1815 return true; 1816 } 1817 if (o == null || !(o instanceof Path)) { 1818 return false; 1819 } 1820 Path path = (Path) o; 1821 return Objects.equals(mRootId, path.mRootId) && 1822 Objects.equals(mPath, path.mPath); 1823 } 1824 1825 @Override hashCode()1826 public int hashCode() { 1827 return Objects.hash(mRootId, mPath); 1828 } 1829 1830 @Override toString()1831 public String toString() { 1832 return new StringBuilder() 1833 .append("DocumentsContract.Path{") 1834 .append("rootId=") 1835 .append(mRootId) 1836 .append(", path=") 1837 .append(mPath) 1838 .append("}") 1839 .toString(); 1840 } 1841 1842 @Override writeToParcel(Parcel dest, int flags)1843 public void writeToParcel(Parcel dest, int flags) { 1844 dest.writeString(mRootId); 1845 dest.writeStringList(mPath); 1846 } 1847 1848 @Override describeContents()1849 public int describeContents() { 1850 return 0; 1851 } 1852 1853 public static final @android.annotation.NonNull Creator<Path> CREATOR = new Creator<Path>() { 1854 @Override 1855 public Path createFromParcel(Parcel in) { 1856 final String rootId = in.readString(); 1857 final List<String> path = in.createStringArrayList(); 1858 return new Path(rootId, path); 1859 } 1860 1861 @Override 1862 public Path[] newArray(int size) { 1863 return new Path[size]; 1864 } 1865 }; 1866 } 1867 } 1868