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