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