DownloadManager.java revision d58429f9acdb33f05bdb233b7bba495de80cb336
1/*
2 * Copyright (C) 2010 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.app;
18
19import android.content.ContentResolver;
20import android.content.ContentUris;
21import android.content.ContentValues;
22import android.content.Context;
23import android.database.Cursor;
24import android.database.CursorWrapper;
25import android.net.ConnectivityManager;
26import android.net.Uri;
27import android.os.Environment;
28import android.os.ParcelFileDescriptor;
29import android.provider.BaseColumns;
30import android.provider.Downloads;
31import android.util.Pair;
32
33import java.io.File;
34import java.io.FileNotFoundException;
35import java.util.ArrayList;
36import java.util.Arrays;
37import java.util.HashSet;
38import java.util.List;
39import java.util.Set;
40
41/**
42 * The download manager is a system service that handles long-running HTTP downloads. Clients may
43 * request that a URI be downloaded to a particular destination file. The download manager will
44 * conduct the download in the background, taking care of HTTP interactions and retrying downloads
45 * after failures or across connectivity changes and system reboots.
46 *
47 * Instances of this class should be obtained through
48 * {@link android.content.Context#getSystemService(String)} by passing
49 * {@link android.content.Context#DOWNLOAD_SERVICE}.
50 */
51public class DownloadManager {
52    /**
53     * An identifier for a particular download, unique across the system.  Clients use this ID to
54     * make subsequent calls related to the download.
55     */
56    public final static String COLUMN_ID = BaseColumns._ID;
57
58    /**
59     * The client-supplied title for this download.  This will be displayed in system notifications.
60     * Defaults to the empty string.
61     */
62    public final static String COLUMN_TITLE = "title";
63
64    /**
65     * The client-supplied description of this download.  This will be displayed in system
66     * notifications.  Defaults to the empty string.
67     */
68    public final static String COLUMN_DESCRIPTION = "description";
69
70    /**
71     * URI to be downloaded.
72     */
73    public final static String COLUMN_URI = "uri";
74
75    /**
76     * Internet Media Type of the downloaded file.  If no value is provided upon creation, this will
77     * initially be null and will be filled in based on the server's response once the download has
78     * started.
79     *
80     * @see <a href="http://www.ietf.org/rfc/rfc1590.txt">RFC 1590, defining Media Types</a>
81     */
82    public final static String COLUMN_MEDIA_TYPE = "media_type";
83
84    /**
85     * Total size of the download in bytes.  This will initially be -1 and will be filled in once
86     * the download starts.
87     */
88    public final static String COLUMN_TOTAL_SIZE_BYTES = "total_size";
89
90    /**
91     * Uri where downloaded file will be stored.  If a destination is supplied by client, that URI
92     * will be used here.  Otherwise, the value will initially be null and will be filled in with a
93     * generated URI once the download has started.
94     */
95    public final static String COLUMN_LOCAL_URI = "local_uri";
96
97    /**
98     * Current status of the download, as one of the STATUS_* constants.
99     */
100    public final static String COLUMN_STATUS = "status";
101
102    /**
103     * Indicates the type of error that occurred, when {@link #COLUMN_STATUS} is
104     * {@link #STATUS_FAILED}.  If an HTTP error occurred, this will hold the HTTP status code as
105     * defined in RFC 2616.  Otherwise, it will hold one of the ERROR_* constants.
106     *
107     * If {@link #COLUMN_STATUS} is not {@link #STATUS_FAILED}, this column's value is undefined.
108     *
109     * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1.1">RFC 2616
110     * status codes</a>
111     */
112    public final static String COLUMN_ERROR_CODE = "error_code";
113
114    /**
115     * Number of bytes download so far.
116     */
117    public final static String COLUMN_BYTES_DOWNLOADED_SO_FAR = "bytes_so_far";
118
119    /**
120     * Timestamp when the download was last modified, in {@link System#currentTimeMillis
121     * System.currentTimeMillis()} (wall clock time in UTC).
122     */
123    public final static String COLUMN_LAST_MODIFIED_TIMESTAMP = "last_modified_timestamp";
124
125
126    /**
127     * Value of {@link #COLUMN_STATUS} when the download is waiting to start.
128     */
129    public final static int STATUS_PENDING = 1 << 0;
130
131    /**
132     * Value of {@link #COLUMN_STATUS} when the download is currently running.
133     */
134    public final static int STATUS_RUNNING = 1 << 1;
135
136    /**
137     * Value of {@link #COLUMN_STATUS} when the download is waiting to retry or resume.
138     */
139    public final static int STATUS_PAUSED = 1 << 2;
140
141    /**
142     * Value of {@link #COLUMN_STATUS} when the download has successfully completed.
143     */
144    public final static int STATUS_SUCCESSFUL = 1 << 3;
145
146    /**
147     * Value of {@link #COLUMN_STATUS} when the download has failed (and will not be retried).
148     */
149    public final static int STATUS_FAILED = 1 << 4;
150
151
152    /**
153     * Value of COLUMN_ERROR_CODE when the download has completed with an error that doesn't fit
154     * under any other error code.
155     */
156    public final static int ERROR_UNKNOWN = 1000;
157
158    /**
159     * Value of {@link #COLUMN_ERROR_CODE} when a storage issue arises which doesn't fit under any
160     * other error code. Use the more specific {@link #ERROR_INSUFFICIENT_SPACE} and
161     * {@link #ERROR_DEVICE_NOT_FOUND} when appropriate.
162     */
163    public final static int ERROR_FILE_ERROR = 1001;
164
165    /**
166     * Value of {@link #COLUMN_ERROR_CODE} when an HTTP code was received that download manager
167     * can't handle.
168     */
169    public final static int ERROR_UNHANDLED_HTTP_CODE = 1002;
170
171    /**
172     * Value of {@link #COLUMN_ERROR_CODE} when an error receiving or processing data occurred at
173     * the HTTP level.
174     */
175    public final static int ERROR_HTTP_DATA_ERROR = 1004;
176
177    /**
178     * Value of {@link #COLUMN_ERROR_CODE} when there were too many redirects.
179     */
180    public final static int ERROR_TOO_MANY_REDIRECTS = 1005;
181
182    /**
183     * Value of {@link #COLUMN_ERROR_CODE} when there was insufficient storage space. Typically,
184     * this is because the SD card is full.
185     */
186    public final static int ERROR_INSUFFICIENT_SPACE = 1006;
187
188    /**
189     * Value of {@link #COLUMN_ERROR_CODE} when no external storage device was found. Typically,
190     * this is because the SD card is not mounted.
191     */
192    public final static int ERROR_DEVICE_NOT_FOUND = 1007;
193
194    /**
195     * Value of {@link #COLUMN_ERROR_CODE} when some possibly transient error occurred but we can't
196     * resume the download.
197     */
198    public final static int ERROR_CANNOT_RESUME = 1008;
199
200    /**
201     * Value of {@link #COLUMN_ERROR_CODE} when the requested destination file already exists (the
202     * download manager will not overwrite an existing file).
203     */
204    public final static int ERROR_FILE_ALREADY_EXISTS = 1009;
205
206    /**
207     * Broadcast intent action sent by the download manager when a download completes.
208     */
209    public final static String ACTION_DOWNLOAD_COMPLETE = "android.intent.action.DOWNLOAD_COMPLETE";
210
211    /**
212     * Broadcast intent action sent by the download manager when a running download notification is
213     * clicked.
214     */
215    public final static String ACTION_NOTIFICATION_CLICKED =
216            "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED";
217
218    /**
219     * Intent action to launch an activity to display all downloads.
220     */
221    public final static String ACTION_VIEW_DOWNLOADS = "android.intent.action.VIEW_DOWNLOADS";
222
223    /**
224     * Intent extra included with {@link #ACTION_DOWNLOAD_COMPLETE} intents, indicating the ID (as a
225     * long) of the download that just completed.
226     */
227    public static final String EXTRA_DOWNLOAD_ID = "extra_download_id";
228
229    // this array must contain all public columns
230    private static final String[] COLUMNS = new String[] {
231        COLUMN_ID,
232        COLUMN_TITLE,
233        COLUMN_DESCRIPTION,
234        COLUMN_URI,
235        COLUMN_MEDIA_TYPE,
236        COLUMN_TOTAL_SIZE_BYTES,
237        COLUMN_LOCAL_URI,
238        COLUMN_STATUS,
239        COLUMN_ERROR_CODE,
240        COLUMN_BYTES_DOWNLOADED_SO_FAR,
241        COLUMN_LAST_MODIFIED_TIMESTAMP
242    };
243
244    // columns to request from DownloadProvider
245    private static final String[] UNDERLYING_COLUMNS = new String[] {
246        Downloads.Impl._ID,
247        Downloads.COLUMN_TITLE,
248        Downloads.COLUMN_DESCRIPTION,
249        Downloads.COLUMN_URI,
250        Downloads.COLUMN_MIME_TYPE,
251        Downloads.COLUMN_TOTAL_BYTES,
252        Downloads.COLUMN_STATUS,
253        Downloads.COLUMN_CURRENT_BYTES,
254        Downloads.COLUMN_LAST_MODIFICATION,
255        Downloads.COLUMN_DESTINATION,
256        Downloads.Impl.COLUMN_FILE_NAME_HINT,
257        Downloads.Impl._DATA,
258    };
259
260    private static final Set<String> LONG_COLUMNS = new HashSet<String>(
261            Arrays.asList(COLUMN_ID, COLUMN_TOTAL_SIZE_BYTES, COLUMN_STATUS, COLUMN_ERROR_CODE,
262                          COLUMN_BYTES_DOWNLOADED_SO_FAR, COLUMN_LAST_MODIFIED_TIMESTAMP));
263
264    /**
265     * This class contains all the information necessary to request a new download. The URI is the
266     * only required parameter.
267     *
268     * Note that the default download destination is a shared volume where the system might delete
269     * your file if it needs to reclaim space for system use. If this is a problem, use a location
270     * on external storage (see {@link #setDestinationUri(Uri)}.
271     */
272    public static class Request {
273        /**
274         * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
275         * {@link ConnectivityManager#TYPE_MOBILE}.
276         */
277        public static final int NETWORK_MOBILE = 1 << 0;
278
279        /**
280         * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
281         * {@link ConnectivityManager#TYPE_WIFI}.
282         */
283        public static final int NETWORK_WIFI = 1 << 1;
284
285        private Uri mUri;
286        private Uri mDestinationUri;
287        private List<Pair<String, String>> mRequestHeaders = new ArrayList<Pair<String, String>>();
288        private CharSequence mTitle;
289        private CharSequence mDescription;
290        private boolean mShowNotification = true;
291        private String mMimeType;
292        private boolean mRoamingAllowed = true;
293        private int mAllowedNetworkTypes = ~0; // default to all network types allowed
294        private boolean mIsVisibleInDownloadsUi = true;
295
296        /**
297         * @param uri the HTTP URI to download.
298         */
299        public Request(Uri uri) {
300            if (uri == null) {
301                throw new NullPointerException();
302            }
303            String scheme = uri.getScheme();
304            if (scheme == null || (!scheme.equals("http") && !scheme.equals("https"))) {
305                throw new IllegalArgumentException("Can only download HTTP/HTTPS URIs: " + uri);
306            }
307            mUri = uri;
308        }
309
310        /**
311         * Set the local destination for the downloaded file. Must be a file URI to a path on
312         * external storage, and the calling application must have the WRITE_EXTERNAL_STORAGE
313         * permission.
314         *
315         * By default, downloads are saved to a generated filename in the shared download cache and
316         * may be deleted by the system at any time to reclaim space.
317         *
318         * @return this object
319         */
320        public Request setDestinationUri(Uri uri) {
321            mDestinationUri = uri;
322            return this;
323        }
324
325        /**
326         * Set the local destination for the downloaded file to a path within the application's
327         * external files directory (as returned by {@link Context#getExternalFilesDir(String)}.
328         *
329         * @param context the {@link Context} to use in determining the external files directory
330         * @param dirType the directory type to pass to {@link Context#getExternalFilesDir(String)}
331         * @param subPath the path within the external directory, including the destination filename
332         * @return this object
333         */
334        public Request setDestinationInExternalFilesDir(Context context, String dirType,
335                String subPath) {
336            setDestinationFromBase(context.getExternalFilesDir(dirType), subPath);
337            return this;
338        }
339
340        /**
341         * Set the local destination for the downloaded file to a path within the public external
342         * storage directory (as returned by
343         * {@link Environment#getExternalStoragePublicDirectory(String)}.
344         *
345         * @param dirType the directory type to pass to
346         *        {@link Environment#getExternalStoragePublicDirectory(String)}
347         * @param subPath the path within the external directory, including the destination filename
348         * @return this object
349         */
350        public Request setDestinationInExternalPublicDir(String dirType, String subPath) {
351            setDestinationFromBase(Environment.getExternalStoragePublicDirectory(dirType), subPath);
352            return this;
353        }
354
355        private void setDestinationFromBase(File base, String subPath) {
356            if (subPath == null) {
357                throw new NullPointerException("subPath cannot be null");
358            }
359            mDestinationUri = Uri.withAppendedPath(Uri.fromFile(base), subPath);
360        }
361
362        /**
363         * Add an HTTP header to be included with the download request.  The header will be added to
364         * the end of the list.
365         * @param header HTTP header name
366         * @param value header value
367         * @return this object
368         * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2">HTTP/1.1
369         *      Message Headers</a>
370         */
371        public Request addRequestHeader(String header, String value) {
372            if (header == null) {
373                throw new NullPointerException("header cannot be null");
374            }
375            if (header.contains(":")) {
376                throw new IllegalArgumentException("header may not contain ':'");
377            }
378            if (value == null) {
379                value = "";
380            }
381            mRequestHeaders.add(Pair.create(header, value));
382            return this;
383        }
384
385        /**
386         * Set the title of this download, to be displayed in notifications (if enabled)
387         * @return this object
388         */
389        public Request setTitle(CharSequence title) {
390            mTitle = title;
391            return this;
392        }
393
394        /**
395         * Set a description of this download, to be displayed in notifications (if enabled)
396         * @return this object
397         */
398        public Request setDescription(CharSequence description) {
399            mDescription = description;
400            return this;
401        }
402
403        /**
404         * Set the MIME content type of this download.  This will override the content type declared
405         * in the server's response.
406         * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7">HTTP/1.1
407         *      Media Types</a>
408         * @return this object
409         */
410        public Request setMimeType(String mimeType) {
411            mMimeType = mimeType;
412            return this;
413        }
414
415        /**
416         * Control whether a system notification is posted by the download manager while this
417         * download is running. If enabled, the download manager posts notifications about downloads
418         * through the system {@link android.app.NotificationManager}. By default, a notification is
419         * shown.
420         *
421         * If set to false, this requires the permission
422         * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
423         *
424         * @param show whether the download manager should show a notification for this download.
425         * @return this object
426         */
427        public Request setShowRunningNotification(boolean show) {
428            mShowNotification = show;
429            return this;
430        }
431
432        /**
433         * Restrict the types of networks over which this download may proceed.  By default, all
434         * network types are allowed.
435         * @param flags any combination of the NETWORK_* bit flags.
436         * @return this object
437         */
438        public Request setAllowedNetworkTypes(int flags) {
439            mAllowedNetworkTypes = flags;
440            return this;
441        }
442
443        /**
444         * Set whether this download may proceed over a roaming connection.  By default, roaming is
445         * allowed.
446         * @param allowed whether to allow a roaming connection to be used
447         * @return this object
448         */
449        public Request setAllowedOverRoaming(boolean allowed) {
450            mRoamingAllowed = allowed;
451            return this;
452        }
453
454        /**
455         * Set whether this download should be displayed in the system's Downloads UI. True by
456         * default.
457         * @param isVisible whether to display this download in the Downloads UI
458         * @return this object
459         */
460        public Request setVisibleInDownloadsUi(boolean isVisible) {
461            mIsVisibleInDownloadsUi = isVisible;
462            return this;
463        }
464
465        /**
466         * @return ContentValues to be passed to DownloadProvider.insert()
467         */
468        ContentValues toContentValues(String packageName) {
469            ContentValues values = new ContentValues();
470            assert mUri != null;
471            values.put(Downloads.COLUMN_URI, mUri.toString());
472            values.put(Downloads.Impl.COLUMN_IS_PUBLIC_API, true);
473            values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE, packageName);
474
475            if (mDestinationUri != null) {
476                values.put(Downloads.COLUMN_DESTINATION, Downloads.Impl.DESTINATION_FILE_URI);
477                values.put(Downloads.COLUMN_FILE_NAME_HINT, mDestinationUri.toString());
478            } else {
479                values.put(Downloads.COLUMN_DESTINATION,
480                           Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE);
481            }
482
483            if (!mRequestHeaders.isEmpty()) {
484                encodeHttpHeaders(values);
485            }
486
487            putIfNonNull(values, Downloads.COLUMN_TITLE, mTitle);
488            putIfNonNull(values, Downloads.COLUMN_DESCRIPTION, mDescription);
489            putIfNonNull(values, Downloads.COLUMN_MIME_TYPE, mMimeType);
490
491            values.put(Downloads.COLUMN_VISIBILITY,
492                    mShowNotification ? Downloads.VISIBILITY_VISIBLE
493                            : Downloads.VISIBILITY_HIDDEN);
494
495            values.put(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES, mAllowedNetworkTypes);
496            values.put(Downloads.Impl.COLUMN_ALLOW_ROAMING, mRoamingAllowed);
497            values.put(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, mIsVisibleInDownloadsUi);
498
499            return values;
500        }
501
502        private void encodeHttpHeaders(ContentValues values) {
503            int index = 0;
504            for (Pair<String, String> header : mRequestHeaders) {
505                String headerString = header.first + ": " + header.second;
506                values.put(Downloads.Impl.RequestHeaders.INSERT_KEY_PREFIX + index, headerString);
507                index++;
508            }
509        }
510
511        private void putIfNonNull(ContentValues contentValues, String key, Object value) {
512            if (value != null) {
513                contentValues.put(key, value.toString());
514            }
515        }
516    }
517
518    /**
519     * This class may be used to filter download manager queries.
520     */
521    public static class Query {
522        /**
523         * Constant for use with {@link #orderBy}
524         * @hide
525         */
526        public static final int ORDER_ASCENDING = 1;
527
528        /**
529         * Constant for use with {@link #orderBy}
530         * @hide
531         */
532        public static final int ORDER_DESCENDING = 2;
533
534        private Long mId = null;
535        private Integer mStatusFlags = null;
536        private String mOrderByColumn = Downloads.COLUMN_LAST_MODIFICATION;
537        private int mOrderDirection = ORDER_DESCENDING;
538        private boolean mOnlyIncludeVisibleInDownloadsUi = false;
539
540        /**
541         * Include only the download with the given ID.
542         * @return this object
543         */
544        public Query setFilterById(long id) {
545            mId = id;
546            return this;
547        }
548
549        /**
550         * Include only downloads with status matching any the given status flags.
551         * @param flags any combination of the STATUS_* bit flags
552         * @return this object
553         */
554        public Query setFilterByStatus(int flags) {
555            mStatusFlags = flags;
556            return this;
557        }
558
559        /**
560         * Controls whether this query includes downloads not visible in the system's Downloads UI.
561         * @param value if true, this query will only include downloads that should be displayed in
562         *            the system's Downloads UI; if false (the default), this query will include
563         *            both visible and invisible downloads.
564         * @return this object
565         * @hide
566         */
567        public Query setOnlyIncludeVisibleInDownloadsUi(boolean value) {
568            mOnlyIncludeVisibleInDownloadsUi = value;
569            return this;
570        }
571
572        /**
573         * Change the sort order of the returned Cursor.
574         *
575         * @param column one of the COLUMN_* constants; currently, only
576         *         {@link #COLUMN_LAST_MODIFIED_TIMESTAMP} and {@link #COLUMN_TOTAL_SIZE_BYTES} are
577         *         supported.
578         * @param direction either {@link #ORDER_ASCENDING} or {@link #ORDER_DESCENDING}
579         * @return this object
580         * @hide
581         */
582        public Query orderBy(String column, int direction) {
583            if (direction != ORDER_ASCENDING && direction != ORDER_DESCENDING) {
584                throw new IllegalArgumentException("Invalid direction: " + direction);
585            }
586
587            if (column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP)) {
588                mOrderByColumn = Downloads.COLUMN_LAST_MODIFICATION;
589            } else if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) {
590                mOrderByColumn = Downloads.COLUMN_TOTAL_BYTES;
591            } else {
592                throw new IllegalArgumentException("Cannot order by " + column);
593            }
594            mOrderDirection = direction;
595            return this;
596        }
597
598        /**
599         * Run this query using the given ContentResolver.
600         * @param projection the projection to pass to ContentResolver.query()
601         * @return the Cursor returned by ContentResolver.query()
602         */
603        Cursor runQuery(ContentResolver resolver, String[] projection, Uri baseUri) {
604            Uri uri = baseUri;
605            List<String> selectionParts = new ArrayList<String>();
606
607            if (mId != null) {
608                uri = ContentUris.withAppendedId(uri, mId);
609            }
610
611            if (mStatusFlags != null) {
612                List<String> parts = new ArrayList<String>();
613                if ((mStatusFlags & STATUS_PENDING) != 0) {
614                    parts.add(statusClause("=", Downloads.STATUS_PENDING));
615                }
616                if ((mStatusFlags & STATUS_RUNNING) != 0) {
617                    parts.add(statusClause("=", Downloads.STATUS_RUNNING));
618                }
619                if ((mStatusFlags & STATUS_PAUSED) != 0) {
620                    parts.add(statusClause("=", Downloads.STATUS_PENDING_PAUSED));
621                    parts.add(statusClause("=", Downloads.STATUS_RUNNING_PAUSED));
622                }
623                if ((mStatusFlags & STATUS_SUCCESSFUL) != 0) {
624                    parts.add(statusClause("=", Downloads.STATUS_SUCCESS));
625                }
626                if ((mStatusFlags & STATUS_FAILED) != 0) {
627                    parts.add("(" + statusClause(">=", 400)
628                              + " AND " + statusClause("<", 600) + ")");
629                }
630                selectionParts.add(joinStrings(" OR ", parts));
631            }
632
633            if (mOnlyIncludeVisibleInDownloadsUi) {
634                selectionParts.add(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI + " != '0'");
635            }
636
637            String selection = joinStrings(" AND ", selectionParts);
638            String orderDirection = (mOrderDirection == ORDER_ASCENDING ? "ASC" : "DESC");
639            String orderBy = mOrderByColumn + " " + orderDirection;
640
641            return resolver.query(uri, projection, selection, null, orderBy);
642        }
643
644        private String joinStrings(String joiner, Iterable<String> parts) {
645            StringBuilder builder = new StringBuilder();
646            boolean first = true;
647            for (String part : parts) {
648                if (!first) {
649                    builder.append(joiner);
650                }
651                builder.append(part);
652                first = false;
653            }
654            return builder.toString();
655        }
656
657        private String statusClause(String operator, int value) {
658            return Downloads.COLUMN_STATUS + operator + "'" + value + "'";
659        }
660    }
661
662    private ContentResolver mResolver;
663    private String mPackageName;
664    private Uri mBaseUri = Downloads.Impl.CONTENT_URI;
665
666    /**
667     * @hide
668     */
669    public DownloadManager(ContentResolver resolver, String packageName) {
670        mResolver = resolver;
671        mPackageName = packageName;
672    }
673
674    /**
675     * Makes this object access the download provider through /all_downloads URIs rather than
676     * /my_downloads URIs, for clients that have permission to do so.
677     * @hide
678     */
679    public void setAccessAllDownloads(boolean accessAllDownloads) {
680        if (accessAllDownloads) {
681            mBaseUri = Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI;
682        } else {
683            mBaseUri = Downloads.Impl.CONTENT_URI;
684        }
685    }
686
687    /**
688     * Enqueue a new download.  The download will start automatically once the download manager is
689     * ready to execute it and connectivity is available.
690     *
691     * @param request the parameters specifying this download
692     * @return an ID for the download, unique across the system.  This ID is used to make future
693     * calls related to this download.
694     */
695    public long enqueue(Request request) {
696        ContentValues values = request.toContentValues(mPackageName);
697        Uri downloadUri = mResolver.insert(Downloads.CONTENT_URI, values);
698        long id = Long.parseLong(downloadUri.getLastPathSegment());
699        return id;
700    }
701
702    /**
703     * Cancel a download and remove it from the download manager.  The download will be stopped if
704     * it was running, and it will no longer be accessible through the download manager.  If a file
705     * was already downloaded, it will not be deleted.
706     *
707     * @param id the ID of the download
708     */
709    public void remove(long id) {
710        int numDeleted = mResolver.delete(getDownloadUri(id), null, null);
711        if (numDeleted == 0) {
712            throw new IllegalArgumentException("Download " + id + " does not exist");
713        }
714    }
715
716    /**
717     * Query the download manager about downloads that have been requested.
718     * @param query parameters specifying filters for this query
719     * @return a Cursor over the result set of downloads, with columns consisting of all the
720     * COLUMN_* constants.
721     */
722    public Cursor query(Query query) {
723        Cursor underlyingCursor = query.runQuery(mResolver, UNDERLYING_COLUMNS, mBaseUri);
724        if (underlyingCursor == null) {
725            return null;
726        }
727        return new CursorTranslator(underlyingCursor, mBaseUri);
728    }
729
730    /**
731     * Open a downloaded file for reading.  The download must have completed.
732     * @param id the ID of the download
733     * @return a read-only {@link ParcelFileDescriptor}
734     * @throws FileNotFoundException if the destination file does not already exist
735     */
736    public ParcelFileDescriptor openDownloadedFile(long id) throws FileNotFoundException {
737        return mResolver.openFileDescriptor(getDownloadUri(id), "r");
738    }
739
740    /**
741     * Restart the given download, which must have already completed (successfully or not).  This
742     * method will only work when called from within the download manager's process.
743     * @param id the ID of the download
744     * @hide
745     */
746    public void restartDownload(long id) {
747        Cursor cursor = query(new Query().setFilterById(id));
748        try {
749            if (!cursor.moveToFirst()) {
750                throw new IllegalArgumentException("No download with id " + id);
751            }
752            int status = cursor.getInt(cursor.getColumnIndex(COLUMN_STATUS));
753            if (status != STATUS_SUCCESSFUL && status != STATUS_FAILED) {
754                throw new IllegalArgumentException("Cannot restart incomplete download: " + id);
755            }
756        } finally {
757            cursor.close();
758        }
759
760        ContentValues values = new ContentValues();
761        values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, 0);
762        values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, -1);
763        values.putNull(Downloads.Impl._DATA);
764        values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING);
765        mResolver.update(getDownloadUri(id), values, null, null);
766    }
767
768    /**
769     * Get the DownloadProvider URI for the download with the given ID.
770     */
771    Uri getDownloadUri(long id) {
772        return ContentUris.withAppendedId(mBaseUri, id);
773    }
774
775    /**
776     * This class wraps a cursor returned by DownloadProvider -- the "underlying cursor" -- and
777     * presents a different set of columns, those defined in the DownloadManager.COLUMN_* constants.
778     * Some columns correspond directly to underlying values while others are computed from
779     * underlying data.
780     */
781    private static class CursorTranslator extends CursorWrapper {
782        private Uri mBaseUri;
783
784        public CursorTranslator(Cursor cursor, Uri baseUri) {
785            super(cursor);
786            mBaseUri = baseUri;
787        }
788
789        @Override
790        public int getColumnIndex(String columnName) {
791            return Arrays.asList(COLUMNS).indexOf(columnName);
792        }
793
794        @Override
795        public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException {
796            int index = getColumnIndex(columnName);
797            if (index == -1) {
798                throw new IllegalArgumentException("No such column: " + columnName);
799            }
800            return index;
801        }
802
803        @Override
804        public String getColumnName(int columnIndex) {
805            int numColumns = COLUMNS.length;
806            if (columnIndex < 0 || columnIndex >= numColumns) {
807                throw new IllegalArgumentException("Invalid column index " + columnIndex + ", "
808                                                   + numColumns + " columns exist");
809            }
810            return COLUMNS[columnIndex];
811        }
812
813        @Override
814        public String[] getColumnNames() {
815            String[] returnColumns = new String[COLUMNS.length];
816            System.arraycopy(COLUMNS, 0, returnColumns, 0, COLUMNS.length);
817            return returnColumns;
818        }
819
820        @Override
821        public int getColumnCount() {
822            return COLUMNS.length;
823        }
824
825        @Override
826        public byte[] getBlob(int columnIndex) {
827            throw new UnsupportedOperationException();
828        }
829
830        @Override
831        public double getDouble(int columnIndex) {
832            return getLong(columnIndex);
833        }
834
835        private boolean isLongColumn(String column) {
836            return LONG_COLUMNS.contains(column);
837        }
838
839        @Override
840        public float getFloat(int columnIndex) {
841            return (float) getDouble(columnIndex);
842        }
843
844        @Override
845        public int getInt(int columnIndex) {
846            return (int) getLong(columnIndex);
847        }
848
849        @Override
850        public long getLong(int columnIndex) {
851            return translateLong(getColumnName(columnIndex));
852        }
853
854        @Override
855        public short getShort(int columnIndex) {
856            return (short) getLong(columnIndex);
857        }
858
859        @Override
860        public String getString(int columnIndex) {
861            return translateString(getColumnName(columnIndex));
862        }
863
864        private String translateString(String column) {
865            if (isLongColumn(column)) {
866                return Long.toString(translateLong(column));
867            }
868            if (column.equals(COLUMN_TITLE)) {
869                return getUnderlyingString(Downloads.COLUMN_TITLE);
870            }
871            if (column.equals(COLUMN_DESCRIPTION)) {
872                return getUnderlyingString(Downloads.COLUMN_DESCRIPTION);
873            }
874            if (column.equals(COLUMN_URI)) {
875                return getUnderlyingString(Downloads.COLUMN_URI);
876            }
877            if (column.equals(COLUMN_MEDIA_TYPE)) {
878                return getUnderlyingString(Downloads.COLUMN_MIME_TYPE);
879            }
880
881            assert column.equals(COLUMN_LOCAL_URI);
882            return getLocalUri();
883        }
884
885        private String getLocalUri() {
886            long destinationType = getUnderlyingLong(Downloads.Impl.COLUMN_DESTINATION);
887            if (destinationType == Downloads.Impl.DESTINATION_FILE_URI) {
888                // return client-provided file URI for external download
889                return getUnderlyingString(Downloads.Impl.COLUMN_FILE_NAME_HINT);
890            }
891
892            if (destinationType == Downloads.Impl.DESTINATION_EXTERNAL) {
893                // return stored destination for legacy external download
894                return Uri.fromFile(new File(getUnderlyingString(Downloads.Impl._DATA))).toString();
895            }
896
897            // return content URI for cache download
898            long downloadId = getUnderlyingLong(Downloads.Impl._ID);
899            return ContentUris.withAppendedId(mBaseUri, downloadId).toString();
900        }
901
902        private long translateLong(String column) {
903            if (!isLongColumn(column)) {
904                // mimic behavior of underlying cursor -- most likely, throw NumberFormatException
905                return Long.valueOf(translateString(column));
906            }
907
908            if (column.equals(COLUMN_ID)) {
909                return getUnderlyingLong(Downloads.Impl._ID);
910            }
911            if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) {
912                return getUnderlyingLong(Downloads.COLUMN_TOTAL_BYTES);
913            }
914            if (column.equals(COLUMN_STATUS)) {
915                return translateStatus((int) getUnderlyingLong(Downloads.COLUMN_STATUS));
916            }
917            if (column.equals(COLUMN_ERROR_CODE)) {
918                return translateErrorCode((int) getUnderlyingLong(Downloads.COLUMN_STATUS));
919            }
920            if (column.equals(COLUMN_BYTES_DOWNLOADED_SO_FAR)) {
921                return getUnderlyingLong(Downloads.COLUMN_CURRENT_BYTES);
922            }
923            assert column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP);
924            return getUnderlyingLong(Downloads.COLUMN_LAST_MODIFICATION);
925        }
926
927        private long translateErrorCode(int status) {
928            if (translateStatus(status) != STATUS_FAILED) {
929                return 0; // arbitrary value when status is not an error
930            }
931            if ((400 <= status && status < Downloads.Impl.MIN_ARTIFICIAL_ERROR_STATUS)
932                    || (500 <= status && status < 600)) {
933                // HTTP status code
934                return status;
935            }
936
937            switch (status) {
938                case Downloads.STATUS_FILE_ERROR:
939                    return ERROR_FILE_ERROR;
940
941                case Downloads.STATUS_UNHANDLED_HTTP_CODE:
942                case Downloads.STATUS_UNHANDLED_REDIRECT:
943                    return ERROR_UNHANDLED_HTTP_CODE;
944
945                case Downloads.STATUS_HTTP_DATA_ERROR:
946                    return ERROR_HTTP_DATA_ERROR;
947
948                case Downloads.STATUS_TOO_MANY_REDIRECTS:
949                    return ERROR_TOO_MANY_REDIRECTS;
950
951                case Downloads.STATUS_INSUFFICIENT_SPACE_ERROR:
952                    return ERROR_INSUFFICIENT_SPACE;
953
954                case Downloads.STATUS_DEVICE_NOT_FOUND_ERROR:
955                    return ERROR_DEVICE_NOT_FOUND;
956
957                case Downloads.Impl.STATUS_CANNOT_RESUME:
958                    return ERROR_CANNOT_RESUME;
959
960                case Downloads.Impl.STATUS_FILE_ALREADY_EXISTS_ERROR:
961                    return ERROR_FILE_ALREADY_EXISTS;
962
963                default:
964                    return ERROR_UNKNOWN;
965            }
966        }
967
968        private long getUnderlyingLong(String column) {
969            return super.getLong(super.getColumnIndex(column));
970        }
971
972        private String getUnderlyingString(String column) {
973            return super.getString(super.getColumnIndex(column));
974        }
975
976        private long translateStatus(int status) {
977            switch (status) {
978                case Downloads.STATUS_PENDING:
979                    return STATUS_PENDING;
980
981                case Downloads.STATUS_RUNNING:
982                    return STATUS_RUNNING;
983
984                case Downloads.STATUS_PENDING_PAUSED:
985                case Downloads.STATUS_RUNNING_PAUSED:
986                    return STATUS_PAUSED;
987
988                case Downloads.STATUS_SUCCESS:
989                    return STATUS_SUCCESSFUL;
990
991                default:
992                    assert Downloads.isStatusError(status);
993                    return STATUS_FAILED;
994            }
995        }
996    }
997}
998