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