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