blob: 836223eefb97a55c5acd141965b92b385e5b8176 [file] [log] [blame]
Steve Howarda2709362010-07-02 17:12:48 -07001/*
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.net;
18
19import android.content.ContentResolver;
Steve Howardeca77fc2010-09-12 18:49:08 -070020import android.content.ContentUris;
Steve Howarda2709362010-07-02 17:12:48 -070021import android.content.ContentValues;
Steve Howard4f564cd2010-09-22 15:57:25 -070022import android.content.Context;
Steve Howarda2709362010-07-02 17:12:48 -070023import android.database.Cursor;
24import android.database.CursorWrapper;
Steve Howard4f564cd2010-09-22 15:57:25 -070025import android.os.Environment;
Steve Howarda2709362010-07-02 17:12:48 -070026import android.os.ParcelFileDescriptor;
Steve Howardf054e192010-09-01 18:26:26 -070027import android.provider.BaseColumns;
Steve Howarda2709362010-07-02 17:12:48 -070028import android.provider.Downloads;
Steve Howard4f564cd2010-09-22 15:57:25 -070029import android.util.Pair;
Steve Howarda2709362010-07-02 17:12:48 -070030
Steve Howard4f564cd2010-09-22 15:57:25 -070031import java.io.File;
Steve Howarda2709362010-07-02 17:12:48 -070032import java.io.FileNotFoundException;
33import java.util.ArrayList;
34import java.util.Arrays;
Steve Howarda2709362010-07-02 17:12:48 -070035import java.util.HashSet;
36import java.util.List;
Steve Howarda2709362010-07-02 17:12:48 -070037import java.util.Set;
38
39/**
40 * The download manager is a system service that handles long-running HTTP downloads. Clients may
41 * request that a URI be downloaded to a particular destination file. The download manager will
42 * conduct the download in the background, taking care of HTTP interactions and retrying downloads
43 * after failures or across connectivity changes and system reboots.
44 *
45 * Instances of this class should be obtained through
46 * {@link android.content.Context#getSystemService(String)} by passing
47 * {@link android.content.Context#DOWNLOAD_SERVICE}.
Steve Howarda2709362010-07-02 17:12:48 -070048 */
49public class DownloadManager {
50 /**
51 * An identifier for a particular download, unique across the system. Clients use this ID to
52 * make subsequent calls related to the download.
53 */
Steve Howardf054e192010-09-01 18:26:26 -070054 public final static String COLUMN_ID = BaseColumns._ID;
Steve Howarda2709362010-07-02 17:12:48 -070055
56 /**
Steve Howard8651bd52010-08-03 12:35:32 -070057 * The client-supplied title for this download. This will be displayed in system notifications.
58 * Defaults to the empty string.
Steve Howarda2709362010-07-02 17:12:48 -070059 */
60 public final static String COLUMN_TITLE = "title";
61
62 /**
63 * The client-supplied description of this download. This will be displayed in system
Steve Howard8651bd52010-08-03 12:35:32 -070064 * notifications. Defaults to the empty string.
Steve Howarda2709362010-07-02 17:12:48 -070065 */
66 public final static String COLUMN_DESCRIPTION = "description";
67
68 /**
69 * URI to be downloaded.
70 */
71 public final static String COLUMN_URI = "uri";
72
73 /**
Steve Howard8651bd52010-08-03 12:35:32 -070074 * Internet Media Type of the downloaded file. If no value is provided upon creation, this will
75 * initially be null and will be filled in based on the server's response once the download has
76 * started.
Steve Howarda2709362010-07-02 17:12:48 -070077 *
78 * @see <a href="http://www.ietf.org/rfc/rfc1590.txt">RFC 1590, defining Media Types</a>
79 */
80 public final static String COLUMN_MEDIA_TYPE = "media_type";
81
82 /**
Steve Howard8651bd52010-08-03 12:35:32 -070083 * Total size of the download in bytes. This will initially be -1 and will be filled in once
84 * the download starts.
Steve Howarda2709362010-07-02 17:12:48 -070085 */
86 public final static String COLUMN_TOTAL_SIZE_BYTES = "total_size";
87
88 /**
89 * Uri where downloaded file will be stored. If a destination is supplied by client, that URI
Steve Howard8651bd52010-08-03 12:35:32 -070090 * will be used here. Otherwise, the value will initially be null and will be filled in with a
91 * generated URI once the download has started.
Steve Howarda2709362010-07-02 17:12:48 -070092 */
93 public final static String COLUMN_LOCAL_URI = "local_uri";
94
95 /**
96 * Current status of the download, as one of the STATUS_* constants.
97 */
98 public final static String COLUMN_STATUS = "status";
99
100 /**
101 * Indicates the type of error that occurred, when {@link #COLUMN_STATUS} is
102 * {@link #STATUS_FAILED}. If an HTTP error occurred, this will hold the HTTP status code as
103 * defined in RFC 2616. Otherwise, it will hold one of the ERROR_* constants.
104 *
105 * If {@link #COLUMN_STATUS} is not {@link #STATUS_FAILED}, this column's value is undefined.
106 *
107 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1.1">RFC 2616
108 * status codes</a>
109 */
110 public final static String COLUMN_ERROR_CODE = "error_code";
111
112 /**
113 * Number of bytes download so far.
114 */
115 public final static String COLUMN_BYTES_DOWNLOADED_SO_FAR = "bytes_so_far";
116
117 /**
Steve Howardadcb6972010-07-12 17:09:25 -0700118 * Timestamp when the download was last modified, in {@link System#currentTimeMillis
Steve Howarda2709362010-07-02 17:12:48 -0700119 * System.currentTimeMillis()} (wall clock time in UTC).
120 */
Steve Howardadcb6972010-07-12 17:09:25 -0700121 public final static String COLUMN_LAST_MODIFIED_TIMESTAMP = "last_modified_timestamp";
Steve Howarda2709362010-07-02 17:12:48 -0700122
123
124 /**
125 * Value of {@link #COLUMN_STATUS} when the download is waiting to start.
126 */
127 public final static int STATUS_PENDING = 1 << 0;
128
129 /**
130 * Value of {@link #COLUMN_STATUS} when the download is currently running.
131 */
132 public final static int STATUS_RUNNING = 1 << 1;
133
134 /**
135 * Value of {@link #COLUMN_STATUS} when the download is waiting to retry or resume.
136 */
137 public final static int STATUS_PAUSED = 1 << 2;
138
139 /**
140 * Value of {@link #COLUMN_STATUS} when the download has successfully completed.
141 */
142 public final static int STATUS_SUCCESSFUL = 1 << 3;
143
144 /**
145 * Value of {@link #COLUMN_STATUS} when the download has failed (and will not be retried).
146 */
147 public final static int STATUS_FAILED = 1 << 4;
148
149
150 /**
151 * Value of COLUMN_ERROR_CODE when the download has completed with an error that doesn't fit
152 * under any other error code.
153 */
154 public final static int ERROR_UNKNOWN = 1000;
155
156 /**
157 * Value of {@link #COLUMN_ERROR_CODE} when a storage issue arises which doesn't fit under any
158 * other error code. Use the more specific {@link #ERROR_INSUFFICIENT_SPACE} and
159 * {@link #ERROR_DEVICE_NOT_FOUND} when appropriate.
160 */
161 public final static int ERROR_FILE_ERROR = 1001;
162
163 /**
164 * Value of {@link #COLUMN_ERROR_CODE} when an HTTP code was received that download manager
165 * can't handle.
166 */
167 public final static int ERROR_UNHANDLED_HTTP_CODE = 1002;
168
169 /**
170 * Value of {@link #COLUMN_ERROR_CODE} when an error receiving or processing data occurred at
171 * the HTTP level.
172 */
173 public final static int ERROR_HTTP_DATA_ERROR = 1004;
174
175 /**
176 * Value of {@link #COLUMN_ERROR_CODE} when there were too many redirects.
177 */
178 public final static int ERROR_TOO_MANY_REDIRECTS = 1005;
179
180 /**
181 * Value of {@link #COLUMN_ERROR_CODE} when there was insufficient storage space. Typically,
182 * this is because the SD card is full.
183 */
184 public final static int ERROR_INSUFFICIENT_SPACE = 1006;
185
186 /**
187 * Value of {@link #COLUMN_ERROR_CODE} when no external storage device was found. Typically,
188 * this is because the SD card is not mounted.
189 */
190 public final static int ERROR_DEVICE_NOT_FOUND = 1007;
191
Steve Howardb8e07a52010-07-21 14:53:21 -0700192 /**
Steve Howard33bbd122010-08-02 17:51:29 -0700193 * Value of {@link #COLUMN_ERROR_CODE} when some possibly transient error occurred but we can't
194 * resume the download.
195 */
196 public final static int ERROR_CANNOT_RESUME = 1008;
197
198 /**
Steve Howarda9e87c92010-09-16 12:02:03 -0700199 * Value of {@link #COLUMN_ERROR_CODE} when the requested destination file already exists (the
200 * download manager will not overwrite an existing file).
201 */
202 public final static int ERROR_FILE_ALREADY_EXISTS = 1009;
203
204 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700205 * Broadcast intent action sent by the download manager when a download completes.
206 */
207 public final static String ACTION_DOWNLOAD_COMPLETE = "android.intent.action.DOWNLOAD_COMPLETE";
208
209 /**
210 * Broadcast intent action sent by the download manager when a running download notification is
211 * clicked.
212 */
213 public final static String ACTION_NOTIFICATION_CLICKED =
214 "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED";
215
216 /**
217 * Intent extra included with {@link #ACTION_DOWNLOAD_COMPLETE} intents, indicating the ID (as a
218 * long) of the download that just completed.
219 */
220 public static final String EXTRA_DOWNLOAD_ID = "extra_download_id";
Steve Howarda2709362010-07-02 17:12:48 -0700221
222 // this array must contain all public columns
223 private static final String[] COLUMNS = new String[] {
224 COLUMN_ID,
225 COLUMN_TITLE,
226 COLUMN_DESCRIPTION,
227 COLUMN_URI,
228 COLUMN_MEDIA_TYPE,
229 COLUMN_TOTAL_SIZE_BYTES,
230 COLUMN_LOCAL_URI,
231 COLUMN_STATUS,
232 COLUMN_ERROR_CODE,
233 COLUMN_BYTES_DOWNLOADED_SO_FAR,
Steve Howardadcb6972010-07-12 17:09:25 -0700234 COLUMN_LAST_MODIFIED_TIMESTAMP
Steve Howarda2709362010-07-02 17:12:48 -0700235 };
236
237 // columns to request from DownloadProvider
238 private static final String[] UNDERLYING_COLUMNS = new String[] {
239 Downloads.Impl._ID,
240 Downloads.COLUMN_TITLE,
241 Downloads.COLUMN_DESCRIPTION,
242 Downloads.COLUMN_URI,
243 Downloads.COLUMN_MIME_TYPE,
244 Downloads.COLUMN_TOTAL_BYTES,
Steve Howarda2709362010-07-02 17:12:48 -0700245 Downloads.COLUMN_STATUS,
Steve Howardadcb6972010-07-12 17:09:25 -0700246 Downloads.COLUMN_CURRENT_BYTES,
247 Downloads.COLUMN_LAST_MODIFICATION,
Steve Howarda9e87c92010-09-16 12:02:03 -0700248 Downloads.COLUMN_DESTINATION,
249 Downloads.Impl.COLUMN_FILE_NAME_HINT,
Steve Howarda2709362010-07-02 17:12:48 -0700250 };
251
252 private static final Set<String> LONG_COLUMNS = new HashSet<String>(
253 Arrays.asList(COLUMN_ID, COLUMN_TOTAL_SIZE_BYTES, COLUMN_STATUS, COLUMN_ERROR_CODE,
Steve Howardadcb6972010-07-12 17:09:25 -0700254 COLUMN_BYTES_DOWNLOADED_SO_FAR, COLUMN_LAST_MODIFIED_TIMESTAMP));
Steve Howarda2709362010-07-02 17:12:48 -0700255
256 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700257 * This class contains all the information necessary to request a new download. The URI is the
Steve Howarda2709362010-07-02 17:12:48 -0700258 * only required parameter.
Steve Howard4f564cd2010-09-22 15:57:25 -0700259 *
260 * Note that the default download destination is a shared volume where the system might delete
261 * your file if it needs to reclaim space for system use. If this is a problem, use a location
262 * on external storage (see {@link #setDestinationUri(Uri)}.
Steve Howarda2709362010-07-02 17:12:48 -0700263 */
264 public static class Request {
265 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700266 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
267 * {@link ConnectivityManager#TYPE_MOBILE}.
268 */
269 public static final int NETWORK_MOBILE = 1 << 0;
Steve Howarda2709362010-07-02 17:12:48 -0700270
Steve Howardb8e07a52010-07-21 14:53:21 -0700271 /**
272 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
273 * {@link ConnectivityManager#TYPE_WIFI}.
274 */
275 public static final int NETWORK_WIFI = 1 << 1;
276
Steve Howardb8e07a52010-07-21 14:53:21 -0700277 private Uri mUri;
278 private Uri mDestinationUri;
Steve Howard4f564cd2010-09-22 15:57:25 -0700279 private List<Pair<String, String>> mRequestHeaders = new ArrayList<Pair<String, String>>();
280 private CharSequence mTitle;
281 private CharSequence mDescription;
Steve Howard8e15afe2010-07-28 17:12:40 -0700282 private boolean mShowNotification = true;
Steve Howard4f564cd2010-09-22 15:57:25 -0700283 private String mMimeType;
Steve Howardb8e07a52010-07-21 14:53:21 -0700284 private boolean mRoamingAllowed = true;
285 private int mAllowedNetworkTypes = ~0; // default to all network types allowed
Steve Howard90fb15a2010-09-09 16:13:41 -0700286 private boolean mIsVisibleInDownloadsUi = true;
Steve Howarda2709362010-07-02 17:12:48 -0700287
288 /**
289 * @param uri the HTTP URI to download.
290 */
291 public Request(Uri uri) {
292 if (uri == null) {
293 throw new NullPointerException();
294 }
295 String scheme = uri.getScheme();
296 if (scheme == null || !scheme.equals("http")) {
297 throw new IllegalArgumentException("Can only download HTTP URIs: " + uri);
298 }
299 mUri = uri;
300 }
301
302 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700303 * Set the local destination for the downloaded file. Must be a file URI to a path on
Steve Howarda2709362010-07-02 17:12:48 -0700304 * external storage, and the calling application must have the WRITE_EXTERNAL_STORAGE
305 * permission.
306 *
Steve Howard4f564cd2010-09-22 15:57:25 -0700307 * By default, downloads are saved to a generated filename in the shared download cache and
308 * may be deleted by the system at any time to reclaim space.
Steve Howarda2709362010-07-02 17:12:48 -0700309 *
310 * @return this object
311 */
312 public Request setDestinationUri(Uri uri) {
313 mDestinationUri = uri;
314 return this;
315 }
316
317 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700318 * Set the local destination for the downloaded file to a path within the application's
319 * external files directory (as returned by {@link Context#getExternalFilesDir(String)}.
320 *
321 * @param context the {@link Context} to use in determining the external files directory
322 * @param dirType the directory type to pass to {@link Context#getExternalFilesDir(String)}
323 * @param subPath the path within the external directory, including the destination filename
324 * @return this object
325 */
326 public Request setDestinationInExternalFilesDir(Context context, String dirType,
327 String subPath) {
328 setDestinationFromBase(context.getExternalFilesDir(dirType), subPath);
329 return this;
330 }
331
332 /**
333 * Set the local destination for the downloaded file to a path within the public external
334 * storage directory (as returned by
335 * {@link Environment#getExternalStoragePublicDirectory(String)}.
336 *
337 * @param dirType the directory type to pass to
338 * {@link Environment#getExternalStoragePublicDirectory(String)}
339 * @param subPath the path within the external directory, including the destination filename
340 * @return this object
341 */
342 public Request setDestinationInExternalPublicDir(String dirType, String subPath) {
343 setDestinationFromBase(Environment.getExternalStoragePublicDirectory(dirType), subPath);
344 return this;
345 }
346
347 private void setDestinationFromBase(File base, String subPath) {
348 if (subPath == null) {
349 throw new NullPointerException("subPath cannot be null");
350 }
351 mDestinationUri = Uri.withAppendedPath(Uri.fromFile(base), subPath);
352 }
353
354 /**
355 * Add an HTTP header to be included with the download request. The header will be added to
356 * the end of the list.
Steve Howarda2709362010-07-02 17:12:48 -0700357 * @param header HTTP header name
358 * @param value header value
359 * @return this object
Steve Howard4f564cd2010-09-22 15:57:25 -0700360 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2">HTTP/1.1
361 * Message Headers</a>
Steve Howarda2709362010-07-02 17:12:48 -0700362 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700363 public Request addRequestHeader(String header, String value) {
364 if (header == null) {
365 throw new NullPointerException("header cannot be null");
366 }
367 if (header.contains(":")) {
368 throw new IllegalArgumentException("header may not contain ':'");
369 }
370 if (value == null) {
371 value = "";
372 }
373 mRequestHeaders.add(Pair.create(header, value));
Steve Howarda2709362010-07-02 17:12:48 -0700374 return this;
375 }
376
377 /**
378 * Set the title of this download, to be displayed in notifications (if enabled)
379 * @return this object
380 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700381 public Request setTitle(CharSequence title) {
Steve Howarda2709362010-07-02 17:12:48 -0700382 mTitle = title;
383 return this;
384 }
385
386 /**
387 * Set a description of this download, to be displayed in notifications (if enabled)
388 * @return this object
389 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700390 public Request setDescription(CharSequence description) {
Steve Howarda2709362010-07-02 17:12:48 -0700391 mDescription = description;
392 return this;
393 }
394
395 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700396 * Set the MIME content type of this download. This will override the content type declared
Steve Howarda2709362010-07-02 17:12:48 -0700397 * in the server's response.
Steve Howard4f564cd2010-09-22 15:57:25 -0700398 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7">HTTP/1.1
399 * Media Types</a>
Steve Howarda2709362010-07-02 17:12:48 -0700400 * @return this object
401 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700402 public Request setMimeType(String mimeType) {
403 mMimeType = mimeType;
Steve Howarda2709362010-07-02 17:12:48 -0700404 return this;
405 }
406
407 /**
Steve Howard8e15afe2010-07-28 17:12:40 -0700408 * Control whether a system notification is posted by the download manager while this
409 * download is running. If enabled, the download manager posts notifications about downloads
410 * through the system {@link android.app.NotificationManager}. By default, a notification is
411 * shown.
Steve Howarda2709362010-07-02 17:12:48 -0700412 *
Steve Howard8e15afe2010-07-28 17:12:40 -0700413 * If set to false, this requires the permission
414 * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
415 *
416 * @param show whether the download manager should show a notification for this download.
Steve Howarda2709362010-07-02 17:12:48 -0700417 * @return this object
418 */
Steve Howard8e15afe2010-07-28 17:12:40 -0700419 public Request setShowRunningNotification(boolean show) {
420 mShowNotification = show;
Steve Howarda2709362010-07-02 17:12:48 -0700421 return this;
422 }
423
Steve Howardb8e07a52010-07-21 14:53:21 -0700424 /**
425 * Restrict the types of networks over which this download may proceed. By default, all
426 * network types are allowed.
427 * @param flags any combination of the NETWORK_* bit flags.
428 * @return this object
429 */
Steve Howarda2709362010-07-02 17:12:48 -0700430 public Request setAllowedNetworkTypes(int flags) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700431 mAllowedNetworkTypes = flags;
432 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700433 }
434
Steve Howardb8e07a52010-07-21 14:53:21 -0700435 /**
436 * Set whether this download may proceed over a roaming connection. By default, roaming is
437 * allowed.
438 * @param allowed whether to allow a roaming connection to be used
439 * @return this object
440 */
Steve Howarda2709362010-07-02 17:12:48 -0700441 public Request setAllowedOverRoaming(boolean allowed) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700442 mRoamingAllowed = allowed;
443 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700444 }
445
446 /**
Steve Howard90fb15a2010-09-09 16:13:41 -0700447 * Set whether this download should be displayed in the system's Downloads UI. True by
448 * default.
449 * @param isVisible whether to display this download in the Downloads UI
450 * @return this object
451 */
452 public Request setVisibleInDownloadsUi(boolean isVisible) {
453 mIsVisibleInDownloadsUi = isVisible;
454 return this;
455 }
456
457 /**
Steve Howarda2709362010-07-02 17:12:48 -0700458 * @return ContentValues to be passed to DownloadProvider.insert()
459 */
Steve Howardb8e07a52010-07-21 14:53:21 -0700460 ContentValues toContentValues(String packageName) {
Steve Howarda2709362010-07-02 17:12:48 -0700461 ContentValues values = new ContentValues();
462 assert mUri != null;
463 values.put(Downloads.COLUMN_URI, mUri.toString());
Steve Howardb8e07a52010-07-21 14:53:21 -0700464 values.put(Downloads.Impl.COLUMN_IS_PUBLIC_API, true);
465 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE, packageName);
Steve Howarda2709362010-07-02 17:12:48 -0700466
467 if (mDestinationUri != null) {
Steve Howardadcb6972010-07-12 17:09:25 -0700468 values.put(Downloads.COLUMN_DESTINATION, Downloads.Impl.DESTINATION_FILE_URI);
469 values.put(Downloads.COLUMN_FILE_NAME_HINT, mDestinationUri.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700470 } else {
471 values.put(Downloads.COLUMN_DESTINATION,
472 Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE);
473 }
474
475 if (!mRequestHeaders.isEmpty()) {
Steve Howardea9147d2010-07-13 19:02:45 -0700476 encodeHttpHeaders(values);
Steve Howarda2709362010-07-02 17:12:48 -0700477 }
478
479 putIfNonNull(values, Downloads.COLUMN_TITLE, mTitle);
480 putIfNonNull(values, Downloads.COLUMN_DESCRIPTION, mDescription);
Steve Howard4f564cd2010-09-22 15:57:25 -0700481 putIfNonNull(values, Downloads.COLUMN_MIME_TYPE, mMimeType);
Steve Howarda2709362010-07-02 17:12:48 -0700482
Steve Howard8e15afe2010-07-28 17:12:40 -0700483 values.put(Downloads.COLUMN_VISIBILITY,
484 mShowNotification ? Downloads.VISIBILITY_VISIBLE
485 : Downloads.VISIBILITY_HIDDEN);
Steve Howarda2709362010-07-02 17:12:48 -0700486
Steve Howardb8e07a52010-07-21 14:53:21 -0700487 values.put(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES, mAllowedNetworkTypes);
488 values.put(Downloads.Impl.COLUMN_ALLOW_ROAMING, mRoamingAllowed);
Steve Howard90fb15a2010-09-09 16:13:41 -0700489 values.put(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, mIsVisibleInDownloadsUi);
Steve Howardb8e07a52010-07-21 14:53:21 -0700490
Steve Howarda2709362010-07-02 17:12:48 -0700491 return values;
492 }
493
Steve Howardea9147d2010-07-13 19:02:45 -0700494 private void encodeHttpHeaders(ContentValues values) {
495 int index = 0;
Steve Howard4f564cd2010-09-22 15:57:25 -0700496 for (Pair<String, String> header : mRequestHeaders) {
497 String headerString = header.first + ": " + header.second;
Steve Howardea9147d2010-07-13 19:02:45 -0700498 values.put(Downloads.Impl.RequestHeaders.INSERT_KEY_PREFIX + index, headerString);
499 index++;
500 }
501 }
502
Steve Howard4f564cd2010-09-22 15:57:25 -0700503 private void putIfNonNull(ContentValues contentValues, String key, Object value) {
Steve Howarda2709362010-07-02 17:12:48 -0700504 if (value != null) {
Steve Howard4f564cd2010-09-22 15:57:25 -0700505 contentValues.put(key, value.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700506 }
507 }
508 }
509
510 /**
511 * This class may be used to filter download manager queries.
512 */
513 public static class Query {
Steve Howardf054e192010-09-01 18:26:26 -0700514 /**
515 * Constant for use with {@link #orderBy}
516 * @hide
517 */
518 public static final int ORDER_ASCENDING = 1;
519
520 /**
521 * Constant for use with {@link #orderBy}
522 * @hide
523 */
524 public static final int ORDER_DESCENDING = 2;
525
526 private Long mId = null;
Steve Howarda2709362010-07-02 17:12:48 -0700527 private Integer mStatusFlags = null;
Steve Howardf054e192010-09-01 18:26:26 -0700528 private String mOrderByColumn = Downloads.COLUMN_LAST_MODIFICATION;
529 private int mOrderDirection = ORDER_DESCENDING;
Steve Howard90fb15a2010-09-09 16:13:41 -0700530 private boolean mOnlyIncludeVisibleInDownloadsUi = false;
Steve Howarda2709362010-07-02 17:12:48 -0700531
532 /**
533 * Include only the download with the given ID.
534 * @return this object
535 */
536 public Query setFilterById(long id) {
537 mId = id;
538 return this;
539 }
540
541 /**
542 * Include only downloads with status matching any the given status flags.
543 * @param flags any combination of the STATUS_* bit flags
544 * @return this object
545 */
546 public Query setFilterByStatus(int flags) {
547 mStatusFlags = flags;
548 return this;
549 }
550
551 /**
Steve Howard90fb15a2010-09-09 16:13:41 -0700552 * Controls whether this query includes downloads not visible in the system's Downloads UI.
553 * @param value if true, this query will only include downloads that should be displayed in
554 * the system's Downloads UI; if false (the default), this query will include
555 * both visible and invisible downloads.
556 * @return this object
557 * @hide
558 */
559 public Query setOnlyIncludeVisibleInDownloadsUi(boolean value) {
560 mOnlyIncludeVisibleInDownloadsUi = value;
561 return this;
562 }
563
564 /**
Steve Howardf054e192010-09-01 18:26:26 -0700565 * Change the sort order of the returned Cursor.
566 *
567 * @param column one of the COLUMN_* constants; currently, only
568 * {@link #COLUMN_LAST_MODIFIED_TIMESTAMP} and {@link #COLUMN_TOTAL_SIZE_BYTES} are
569 * supported.
570 * @param direction either {@link #ORDER_ASCENDING} or {@link #ORDER_DESCENDING}
571 * @return this object
572 * @hide
573 */
574 public Query orderBy(String column, int direction) {
575 if (direction != ORDER_ASCENDING && direction != ORDER_DESCENDING) {
576 throw new IllegalArgumentException("Invalid direction: " + direction);
577 }
578
579 if (column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP)) {
580 mOrderByColumn = Downloads.COLUMN_LAST_MODIFICATION;
581 } else if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) {
582 mOrderByColumn = Downloads.COLUMN_TOTAL_BYTES;
583 } else {
584 throw new IllegalArgumentException("Cannot order by " + column);
585 }
586 mOrderDirection = direction;
587 return this;
588 }
589
590 /**
Steve Howarda2709362010-07-02 17:12:48 -0700591 * Run this query using the given ContentResolver.
592 * @param projection the projection to pass to ContentResolver.query()
593 * @return the Cursor returned by ContentResolver.query()
594 */
Steve Howardeca77fc2010-09-12 18:49:08 -0700595 Cursor runQuery(ContentResolver resolver, String[] projection, Uri baseUri) {
596 Uri uri = baseUri;
Steve Howard90fb15a2010-09-09 16:13:41 -0700597 List<String> selectionParts = new ArrayList<String>();
Steve Howarda2709362010-07-02 17:12:48 -0700598
599 if (mId != null) {
Steve Howardeca77fc2010-09-12 18:49:08 -0700600 uri = ContentUris.withAppendedId(uri, mId);
Steve Howarda2709362010-07-02 17:12:48 -0700601 }
602
603 if (mStatusFlags != null) {
604 List<String> parts = new ArrayList<String>();
605 if ((mStatusFlags & STATUS_PENDING) != 0) {
606 parts.add(statusClause("=", Downloads.STATUS_PENDING));
607 }
608 if ((mStatusFlags & STATUS_RUNNING) != 0) {
609 parts.add(statusClause("=", Downloads.STATUS_RUNNING));
610 }
611 if ((mStatusFlags & STATUS_PAUSED) != 0) {
612 parts.add(statusClause("=", Downloads.STATUS_PENDING_PAUSED));
613 parts.add(statusClause("=", Downloads.STATUS_RUNNING_PAUSED));
614 }
615 if ((mStatusFlags & STATUS_SUCCESSFUL) != 0) {
616 parts.add(statusClause("=", Downloads.STATUS_SUCCESS));
617 }
618 if ((mStatusFlags & STATUS_FAILED) != 0) {
619 parts.add("(" + statusClause(">=", 400)
620 + " AND " + statusClause("<", 600) + ")");
621 }
Steve Howard90fb15a2010-09-09 16:13:41 -0700622 selectionParts.add(joinStrings(" OR ", parts));
Steve Howarda2709362010-07-02 17:12:48 -0700623 }
Steve Howardf054e192010-09-01 18:26:26 -0700624
Steve Howard90fb15a2010-09-09 16:13:41 -0700625 if (mOnlyIncludeVisibleInDownloadsUi) {
626 selectionParts.add(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI + " != '0'");
627 }
628
629 String selection = joinStrings(" AND ", selectionParts);
Steve Howardf054e192010-09-01 18:26:26 -0700630 String orderDirection = (mOrderDirection == ORDER_ASCENDING ? "ASC" : "DESC");
631 String orderBy = mOrderByColumn + " " + orderDirection;
632
Steve Howardadcb6972010-07-12 17:09:25 -0700633 return resolver.query(uri, projection, selection, null, orderBy);
Steve Howarda2709362010-07-02 17:12:48 -0700634 }
635
636 private String joinStrings(String joiner, Iterable<String> parts) {
637 StringBuilder builder = new StringBuilder();
638 boolean first = true;
639 for (String part : parts) {
640 if (!first) {
641 builder.append(joiner);
642 }
643 builder.append(part);
644 first = false;
645 }
646 return builder.toString();
647 }
648
649 private String statusClause(String operator, int value) {
650 return Downloads.COLUMN_STATUS + operator + "'" + value + "'";
651 }
652 }
653
654 private ContentResolver mResolver;
Steve Howardb8e07a52010-07-21 14:53:21 -0700655 private String mPackageName;
Steve Howardeca77fc2010-09-12 18:49:08 -0700656 private Uri mBaseUri = Downloads.Impl.CONTENT_URI;
Steve Howarda2709362010-07-02 17:12:48 -0700657
658 /**
659 * @hide
660 */
Steve Howardb8e07a52010-07-21 14:53:21 -0700661 public DownloadManager(ContentResolver resolver, String packageName) {
Steve Howarda2709362010-07-02 17:12:48 -0700662 mResolver = resolver;
Steve Howardb8e07a52010-07-21 14:53:21 -0700663 mPackageName = packageName;
Steve Howarda2709362010-07-02 17:12:48 -0700664 }
665
666 /**
Steve Howardeca77fc2010-09-12 18:49:08 -0700667 * Makes this object access the download provider through /all_downloads URIs rather than
668 * /my_downloads URIs, for clients that have permission to do so.
669 * @hide
670 */
671 public void setAccessAllDownloads(boolean accessAllDownloads) {
672 if (accessAllDownloads) {
673 mBaseUri = Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI;
674 } else {
675 mBaseUri = Downloads.Impl.CONTENT_URI;
676 }
677 }
678
679 /**
Steve Howarda2709362010-07-02 17:12:48 -0700680 * Enqueue a new download. The download will start automatically once the download manager is
681 * ready to execute it and connectivity is available.
682 *
683 * @param request the parameters specifying this download
684 * @return an ID for the download, unique across the system. This ID is used to make future
685 * calls related to this download.
686 */
687 public long enqueue(Request request) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700688 ContentValues values = request.toContentValues(mPackageName);
Steve Howarda2709362010-07-02 17:12:48 -0700689 Uri downloadUri = mResolver.insert(Downloads.CONTENT_URI, values);
690 long id = Long.parseLong(downloadUri.getLastPathSegment());
691 return id;
692 }
693
694 /**
695 * Cancel a download and remove it from the download manager. The download will be stopped if
696 * it was running, and it will no longer be accessible through the download manager. If a file
697 * was already downloaded, it will not be deleted.
698 *
699 * @param id the ID of the download
700 */
701 public void remove(long id) {
702 int numDeleted = mResolver.delete(getDownloadUri(id), null, null);
703 if (numDeleted == 0) {
704 throw new IllegalArgumentException("Download " + id + " does not exist");
705 }
706 }
707
708 /**
709 * Query the download manager about downloads that have been requested.
710 * @param query parameters specifying filters for this query
711 * @return a Cursor over the result set of downloads, with columns consisting of all the
712 * COLUMN_* constants.
713 */
714 public Cursor query(Query query) {
Steve Howardeca77fc2010-09-12 18:49:08 -0700715 Cursor underlyingCursor = query.runQuery(mResolver, UNDERLYING_COLUMNS, mBaseUri);
Steve Howardf054e192010-09-01 18:26:26 -0700716 if (underlyingCursor == null) {
717 return null;
718 }
Steve Howardeca77fc2010-09-12 18:49:08 -0700719 return new CursorTranslator(underlyingCursor, mBaseUri);
Steve Howarda2709362010-07-02 17:12:48 -0700720 }
721
722 /**
723 * Open a downloaded file for reading. The download must have completed.
724 * @param id the ID of the download
725 * @return a read-only {@link ParcelFileDescriptor}
726 * @throws FileNotFoundException if the destination file does not already exist
727 */
728 public ParcelFileDescriptor openDownloadedFile(long id) throws FileNotFoundException {
729 return mResolver.openFileDescriptor(getDownloadUri(id), "r");
730 }
731
732 /**
Steve Howard90fb15a2010-09-09 16:13:41 -0700733 * Restart the given download, which must have already completed (successfully or not). This
734 * method will only work when called from within the download manager's process.
735 * @param id the ID of the download
736 * @hide
737 */
738 public void restartDownload(long id) {
739 Cursor cursor = query(new Query().setFilterById(id));
740 try {
741 if (!cursor.moveToFirst()) {
742 throw new IllegalArgumentException("No download with id " + id);
743 }
744 int status = cursor.getInt(cursor.getColumnIndex(COLUMN_STATUS));
745 if (status != STATUS_SUCCESSFUL && status != STATUS_FAILED) {
746 throw new IllegalArgumentException("Cannot restart incomplete download: " + id);
747 }
748 } finally {
749 cursor.close();
750 }
751
752 ContentValues values = new ContentValues();
753 values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, 0);
754 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, -1);
755 values.putNull(Downloads.Impl._DATA);
756 values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING);
757 mResolver.update(getDownloadUri(id), values, null, null);
758 }
759
760 /**
Steve Howarda2709362010-07-02 17:12:48 -0700761 * Get the DownloadProvider URI for the download with the given ID.
762 */
Steve Howardeca77fc2010-09-12 18:49:08 -0700763 Uri getDownloadUri(long id) {
764 return ContentUris.withAppendedId(mBaseUri, id);
Steve Howarda2709362010-07-02 17:12:48 -0700765 }
766
767 /**
768 * This class wraps a cursor returned by DownloadProvider -- the "underlying cursor" -- and
769 * presents a different set of columns, those defined in the DownloadManager.COLUMN_* constants.
770 * Some columns correspond directly to underlying values while others are computed from
771 * underlying data.
772 */
773 private static class CursorTranslator extends CursorWrapper {
Steve Howardeca77fc2010-09-12 18:49:08 -0700774 private Uri mBaseUri;
775
776 public CursorTranslator(Cursor cursor, Uri baseUri) {
Steve Howarda2709362010-07-02 17:12:48 -0700777 super(cursor);
Steve Howardeca77fc2010-09-12 18:49:08 -0700778 mBaseUri = baseUri;
Steve Howarda2709362010-07-02 17:12:48 -0700779 }
780
781 @Override
782 public int getColumnIndex(String columnName) {
783 return Arrays.asList(COLUMNS).indexOf(columnName);
784 }
785
786 @Override
787 public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException {
788 int index = getColumnIndex(columnName);
789 if (index == -1) {
Steve Howardf054e192010-09-01 18:26:26 -0700790 throw new IllegalArgumentException("No such column: " + columnName);
Steve Howarda2709362010-07-02 17:12:48 -0700791 }
792 return index;
793 }
794
795 @Override
796 public String getColumnName(int columnIndex) {
797 int numColumns = COLUMNS.length;
798 if (columnIndex < 0 || columnIndex >= numColumns) {
799 throw new IllegalArgumentException("Invalid column index " + columnIndex + ", "
800 + numColumns + " columns exist");
801 }
802 return COLUMNS[columnIndex];
803 }
804
805 @Override
806 public String[] getColumnNames() {
807 String[] returnColumns = new String[COLUMNS.length];
808 System.arraycopy(COLUMNS, 0, returnColumns, 0, COLUMNS.length);
809 return returnColumns;
810 }
811
812 @Override
813 public int getColumnCount() {
814 return COLUMNS.length;
815 }
816
817 @Override
818 public byte[] getBlob(int columnIndex) {
819 throw new UnsupportedOperationException();
820 }
821
822 @Override
823 public double getDouble(int columnIndex) {
824 return getLong(columnIndex);
825 }
826
827 private boolean isLongColumn(String column) {
828 return LONG_COLUMNS.contains(column);
829 }
830
831 @Override
832 public float getFloat(int columnIndex) {
833 return (float) getDouble(columnIndex);
834 }
835
836 @Override
837 public int getInt(int columnIndex) {
838 return (int) getLong(columnIndex);
839 }
840
841 @Override
842 public long getLong(int columnIndex) {
843 return translateLong(getColumnName(columnIndex));
844 }
845
846 @Override
847 public short getShort(int columnIndex) {
848 return (short) getLong(columnIndex);
849 }
850
851 @Override
852 public String getString(int columnIndex) {
853 return translateString(getColumnName(columnIndex));
854 }
855
856 private String translateString(String column) {
857 if (isLongColumn(column)) {
858 return Long.toString(translateLong(column));
859 }
860 if (column.equals(COLUMN_TITLE)) {
861 return getUnderlyingString(Downloads.COLUMN_TITLE);
862 }
863 if (column.equals(COLUMN_DESCRIPTION)) {
864 return getUnderlyingString(Downloads.COLUMN_DESCRIPTION);
865 }
866 if (column.equals(COLUMN_URI)) {
867 return getUnderlyingString(Downloads.COLUMN_URI);
868 }
869 if (column.equals(COLUMN_MEDIA_TYPE)) {
870 return getUnderlyingString(Downloads.COLUMN_MIME_TYPE);
871 }
Steve Howard8651bd52010-08-03 12:35:32 -0700872
Steve Howarda2709362010-07-02 17:12:48 -0700873 assert column.equals(COLUMN_LOCAL_URI);
Steve Howardeca77fc2010-09-12 18:49:08 -0700874 return getLocalUri();
875 }
876
877 private String getLocalUri() {
Steve Howardeca77fc2010-09-12 18:49:08 -0700878 long destinationType = getUnderlyingLong(Downloads.Impl.COLUMN_DESTINATION);
879 if (destinationType == Downloads.Impl.DESTINATION_FILE_URI) {
Steve Howarda9e87c92010-09-16 12:02:03 -0700880 // return client-provided file URI for external download
881 return getUnderlyingString(Downloads.Impl.COLUMN_FILE_NAME_HINT);
Steve Howardeca77fc2010-09-12 18:49:08 -0700882 }
883
884 // return content URI for cache download
885 long downloadId = getUnderlyingLong(Downloads.Impl._ID);
886 return ContentUris.withAppendedId(mBaseUri, downloadId).toString();
Steve Howarda2709362010-07-02 17:12:48 -0700887 }
888
889 private long translateLong(String column) {
890 if (!isLongColumn(column)) {
891 // mimic behavior of underlying cursor -- most likely, throw NumberFormatException
892 return Long.valueOf(translateString(column));
893 }
894
895 if (column.equals(COLUMN_ID)) {
896 return getUnderlyingLong(Downloads.Impl._ID);
897 }
898 if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) {
899 return getUnderlyingLong(Downloads.COLUMN_TOTAL_BYTES);
900 }
901 if (column.equals(COLUMN_STATUS)) {
902 return translateStatus((int) getUnderlyingLong(Downloads.COLUMN_STATUS));
903 }
904 if (column.equals(COLUMN_ERROR_CODE)) {
905 return translateErrorCode((int) getUnderlyingLong(Downloads.COLUMN_STATUS));
906 }
907 if (column.equals(COLUMN_BYTES_DOWNLOADED_SO_FAR)) {
908 return getUnderlyingLong(Downloads.COLUMN_CURRENT_BYTES);
909 }
Steve Howardadcb6972010-07-12 17:09:25 -0700910 assert column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP);
911 return getUnderlyingLong(Downloads.COLUMN_LAST_MODIFICATION);
Steve Howarda2709362010-07-02 17:12:48 -0700912 }
913
914 private long translateErrorCode(int status) {
915 if (translateStatus(status) != STATUS_FAILED) {
916 return 0; // arbitrary value when status is not an error
917 }
Steve Howard33bbd122010-08-02 17:51:29 -0700918 if ((400 <= status && status < Downloads.Impl.MIN_ARTIFICIAL_ERROR_STATUS)
919 || (500 <= status && status < 600)) {
Steve Howarda2709362010-07-02 17:12:48 -0700920 // HTTP status code
921 return status;
922 }
923
924 switch (status) {
925 case Downloads.STATUS_FILE_ERROR:
926 return ERROR_FILE_ERROR;
927
928 case Downloads.STATUS_UNHANDLED_HTTP_CODE:
929 case Downloads.STATUS_UNHANDLED_REDIRECT:
930 return ERROR_UNHANDLED_HTTP_CODE;
931
932 case Downloads.STATUS_HTTP_DATA_ERROR:
933 return ERROR_HTTP_DATA_ERROR;
934
935 case Downloads.STATUS_TOO_MANY_REDIRECTS:
936 return ERROR_TOO_MANY_REDIRECTS;
937
938 case Downloads.STATUS_INSUFFICIENT_SPACE_ERROR:
939 return ERROR_INSUFFICIENT_SPACE;
940
941 case Downloads.STATUS_DEVICE_NOT_FOUND_ERROR:
942 return ERROR_DEVICE_NOT_FOUND;
943
Steve Howard33bbd122010-08-02 17:51:29 -0700944 case Downloads.Impl.STATUS_CANNOT_RESUME:
945 return ERROR_CANNOT_RESUME;
946
Steve Howarda9e87c92010-09-16 12:02:03 -0700947 case Downloads.Impl.STATUS_FILE_ALREADY_EXISTS_ERROR:
948 return ERROR_FILE_ALREADY_EXISTS;
949
Steve Howarda2709362010-07-02 17:12:48 -0700950 default:
951 return ERROR_UNKNOWN;
952 }
953 }
954
955 private long getUnderlyingLong(String column) {
956 return super.getLong(super.getColumnIndex(column));
957 }
958
959 private String getUnderlyingString(String column) {
960 return super.getString(super.getColumnIndex(column));
961 }
962
963 private long translateStatus(int status) {
964 switch (status) {
965 case Downloads.STATUS_PENDING:
966 return STATUS_PENDING;
967
968 case Downloads.STATUS_RUNNING:
969 return STATUS_RUNNING;
970
971 case Downloads.STATUS_PENDING_PAUSED:
972 case Downloads.STATUS_RUNNING_PAUSED:
973 return STATUS_PAUSED;
974
975 case Downloads.STATUS_SUCCESS:
976 return STATUS_SUCCESSFUL;
977
978 default:
979 assert Downloads.isStatusError(status);
980 return STATUS_FAILED;
981 }
982 }
983 }
984}