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