blob: 592a63bc5f2c84cd54693535e21d5892db75e736 [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
Steve Howardd58429f2010-09-27 16:32:39 -070017package android.app;
Steve Howarda2709362010-07-02 17:12:48 -070018
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 Howardd58429f2010-09-27 16:32:39 -070025import android.net.ConnectivityManager;
26import android.net.Uri;
Steve Howard4f564cd2010-09-22 15:57:25 -070027import android.os.Environment;
Steve Howarda2709362010-07-02 17:12:48 -070028import android.os.ParcelFileDescriptor;
29import android.provider.Downloads;
Steve Howard4f564cd2010-09-22 15:57:25 -070030import android.util.Pair;
Steve Howarda2709362010-07-02 17:12:48 -070031
Steve Howard4f564cd2010-09-22 15:57:25 -070032import java.io.File;
Steve Howarda2709362010-07-02 17:12:48 -070033import java.io.FileNotFoundException;
34import java.util.ArrayList;
35import java.util.Arrays;
Steve Howarda2709362010-07-02 17:12:48 -070036import java.util.HashSet;
37import java.util.List;
Steve Howarda2709362010-07-02 17:12:48 -070038import java.util.Set;
39
40/**
41 * The download manager is a system service that handles long-running HTTP downloads. Clients may
42 * request that a URI be downloaded to a particular destination file. The download manager will
43 * conduct the download in the background, taking care of HTTP interactions and retrying downloads
44 * after failures or across connectivity changes and system reboots.
45 *
46 * Instances of this class should be obtained through
47 * {@link android.content.Context#getSystemService(String)} by passing
48 * {@link android.content.Context#DOWNLOAD_SERVICE}.
Steve Howard610c4352010-09-30 18:30:04 -070049 *
50 * Apps that request downloads through this API should register a broadcast receiver for
51 * {@link #ACTION_NOTIFICATION_CLICKED} to appropriately handle when the user clicks on a running
52 * download in a notification or from the downloads UI.
Steve Howarda2709362010-07-02 17:12:48 -070053 */
54public class DownloadManager {
Vasu Norie7be6bd2010-10-10 14:58:08 -070055 private static final String TAG = "DownloadManager";
56
Steve Howarda2709362010-07-02 17:12:48 -070057 /**
58 * An identifier for a particular download, unique across the system. Clients use this ID to
59 * make subsequent calls related to the download.
60 */
Vasu Norief7e33b2010-10-20 13:26:02 -070061 public final static String COLUMN_ID = Downloads.Impl._ID;
Steve Howarda2709362010-07-02 17:12:48 -070062
63 /**
Steve Howard8651bd52010-08-03 12:35:32 -070064 * The client-supplied title for this download. This will be displayed in system notifications.
65 * Defaults to the empty string.
Steve Howarda2709362010-07-02 17:12:48 -070066 */
Vasu Norief7e33b2010-10-20 13:26:02 -070067 public final static String COLUMN_TITLE = Downloads.Impl.COLUMN_TITLE;
Steve Howarda2709362010-07-02 17:12:48 -070068
69 /**
70 * The client-supplied description of this download. This will be displayed in system
Steve Howard8651bd52010-08-03 12:35:32 -070071 * notifications. Defaults to the empty string.
Steve Howarda2709362010-07-02 17:12:48 -070072 */
Vasu Norief7e33b2010-10-20 13:26:02 -070073 public final static String COLUMN_DESCRIPTION = Downloads.Impl.COLUMN_DESCRIPTION;
Steve Howarda2709362010-07-02 17:12:48 -070074
75 /**
76 * URI to be downloaded.
77 */
Vasu Norief7e33b2010-10-20 13:26:02 -070078 public final static String COLUMN_URI = Downloads.Impl.COLUMN_URI;
Steve Howarda2709362010-07-02 17:12:48 -070079
80 /**
Steve Howard8651bd52010-08-03 12:35:32 -070081 * Internet Media Type of the downloaded file. If no value is provided upon creation, this will
82 * initially be null and will be filled in based on the server's response once the download has
83 * started.
Steve Howarda2709362010-07-02 17:12:48 -070084 *
85 * @see <a href="http://www.ietf.org/rfc/rfc1590.txt">RFC 1590, defining Media Types</a>
86 */
87 public final static String COLUMN_MEDIA_TYPE = "media_type";
88
89 /**
Steve Howard8651bd52010-08-03 12:35:32 -070090 * Total size of the download in bytes. This will initially be -1 and will be filled in once
91 * the download starts.
Steve Howarda2709362010-07-02 17:12:48 -070092 */
93 public final static String COLUMN_TOTAL_SIZE_BYTES = "total_size";
94
95 /**
96 * Uri where downloaded file will be stored. If a destination is supplied by client, that URI
Steve Howard8651bd52010-08-03 12:35:32 -070097 * will be used here. Otherwise, the value will initially be null and will be filled in with a
98 * generated URI once the download has started.
Steve Howarda2709362010-07-02 17:12:48 -070099 */
100 public final static String COLUMN_LOCAL_URI = "local_uri";
101
102 /**
Doug Zongkeree04af32010-10-08 13:42:16 -0700103 * The pathname of the file where the download is stored.
104 */
105 public final static String COLUMN_LOCAL_FILENAME = "local_filename";
106
107 /**
Steve Howarda2709362010-07-02 17:12:48 -0700108 * Current status of the download, as one of the STATUS_* constants.
109 */
Vasu Norief7e33b2010-10-20 13:26:02 -0700110 public final static String COLUMN_STATUS = Downloads.Impl.COLUMN_STATUS;
Steve Howarda2709362010-07-02 17:12:48 -0700111
112 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700113 * Provides more detail on the status of the download. Its meaning depends on the value of
114 * {@link #COLUMN_STATUS}.
Steve Howarda2709362010-07-02 17:12:48 -0700115 *
Steve Howard3e8c1d32010-09-29 17:03:32 -0700116 * When {@link #COLUMN_STATUS} is {@link #STATUS_FAILED}, this indicates the type of error that
117 * occurred. If an HTTP error occurred, this will hold the HTTP status code as defined in RFC
118 * 2616. Otherwise, it will hold one of the ERROR_* constants.
119 *
120 * When {@link #COLUMN_STATUS} is {@link #STATUS_PAUSED}, this indicates why the download is
121 * paused. It will hold one of the PAUSED_* constants.
122 *
123 * If {@link #COLUMN_STATUS} is neither {@link #STATUS_FAILED} nor {@link #STATUS_PAUSED}, this
124 * column's value is undefined.
Steve Howarda2709362010-07-02 17:12:48 -0700125 *
126 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1.1">RFC 2616
127 * status codes</a>
128 */
Steve Howard3e8c1d32010-09-29 17:03:32 -0700129 public final static String COLUMN_REASON = "reason";
Steve Howarda2709362010-07-02 17:12:48 -0700130
131 /**
132 * Number of bytes download so far.
133 */
134 public final static String COLUMN_BYTES_DOWNLOADED_SO_FAR = "bytes_so_far";
135
136 /**
Steve Howardadcb6972010-07-12 17:09:25 -0700137 * Timestamp when the download was last modified, in {@link System#currentTimeMillis
Steve Howarda2709362010-07-02 17:12:48 -0700138 * System.currentTimeMillis()} (wall clock time in UTC).
139 */
Steve Howardadcb6972010-07-12 17:09:25 -0700140 public final static String COLUMN_LAST_MODIFIED_TIMESTAMP = "last_modified_timestamp";
Steve Howarda2709362010-07-02 17:12:48 -0700141
Vasu Nori216fa222010-10-12 23:08:13 -0700142 /**
143 * The URI to the corresponding entry in MediaProvider for this downloaded entry. It is
144 * used to delete the entries from MediaProvider database when it is deleted from the
145 * downloaded list.
146 */
Vasu Norief7e33b2010-10-20 13:26:02 -0700147 public static final String COLUMN_MEDIAPROVIDER_URI = Downloads.Impl.COLUMN_MEDIAPROVIDER_URI;
Steve Howarda2709362010-07-02 17:12:48 -0700148
149 /**
150 * Value of {@link #COLUMN_STATUS} when the download is waiting to start.
151 */
152 public final static int STATUS_PENDING = 1 << 0;
153
154 /**
155 * Value of {@link #COLUMN_STATUS} when the download is currently running.
156 */
157 public final static int STATUS_RUNNING = 1 << 1;
158
159 /**
160 * Value of {@link #COLUMN_STATUS} when the download is waiting to retry or resume.
161 */
162 public final static int STATUS_PAUSED = 1 << 2;
163
164 /**
165 * Value of {@link #COLUMN_STATUS} when the download has successfully completed.
166 */
167 public final static int STATUS_SUCCESSFUL = 1 << 3;
168
169 /**
170 * Value of {@link #COLUMN_STATUS} when the download has failed (and will not be retried).
171 */
172 public final static int STATUS_FAILED = 1 << 4;
173
174
175 /**
176 * Value of COLUMN_ERROR_CODE when the download has completed with an error that doesn't fit
177 * under any other error code.
178 */
179 public final static int ERROR_UNKNOWN = 1000;
180
181 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700182 * Value of {@link #COLUMN_REASON} when a storage issue arises which doesn't fit under any
Steve Howarda2709362010-07-02 17:12:48 -0700183 * other error code. Use the more specific {@link #ERROR_INSUFFICIENT_SPACE} and
184 * {@link #ERROR_DEVICE_NOT_FOUND} when appropriate.
185 */
186 public final static int ERROR_FILE_ERROR = 1001;
187
188 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700189 * Value of {@link #COLUMN_REASON} when an HTTP code was received that download manager
Steve Howarda2709362010-07-02 17:12:48 -0700190 * can't handle.
191 */
192 public final static int ERROR_UNHANDLED_HTTP_CODE = 1002;
193
194 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700195 * Value of {@link #COLUMN_REASON} when an error receiving or processing data occurred at
Steve Howarda2709362010-07-02 17:12:48 -0700196 * the HTTP level.
197 */
198 public final static int ERROR_HTTP_DATA_ERROR = 1004;
199
200 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700201 * Value of {@link #COLUMN_REASON} when there were too many redirects.
Steve Howarda2709362010-07-02 17:12:48 -0700202 */
203 public final static int ERROR_TOO_MANY_REDIRECTS = 1005;
204
205 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700206 * Value of {@link #COLUMN_REASON} when there was insufficient storage space. Typically,
Steve Howarda2709362010-07-02 17:12:48 -0700207 * this is because the SD card is full.
208 */
209 public final static int ERROR_INSUFFICIENT_SPACE = 1006;
210
211 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700212 * Value of {@link #COLUMN_REASON} when no external storage device was found. Typically,
Steve Howarda2709362010-07-02 17:12:48 -0700213 * this is because the SD card is not mounted.
214 */
215 public final static int ERROR_DEVICE_NOT_FOUND = 1007;
216
Steve Howardb8e07a52010-07-21 14:53:21 -0700217 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700218 * Value of {@link #COLUMN_REASON} when some possibly transient error occurred but we can't
Steve Howard33bbd122010-08-02 17:51:29 -0700219 * resume the download.
220 */
221 public final static int ERROR_CANNOT_RESUME = 1008;
222
223 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700224 * Value of {@link #COLUMN_REASON} when the requested destination file already exists (the
Steve Howarda9e87c92010-09-16 12:02:03 -0700225 * download manager will not overwrite an existing file).
226 */
227 public final static int ERROR_FILE_ALREADY_EXISTS = 1009;
228
229 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700230 * Value of {@link #COLUMN_REASON} when the download is paused because some network error
231 * occurred and the download manager is waiting before retrying the request.
232 */
233 public final static int PAUSED_WAITING_TO_RETRY = 1;
234
235 /**
236 * Value of {@link #COLUMN_REASON} when the download is waiting for network connectivity to
237 * proceed.
238 */
239 public final static int PAUSED_WAITING_FOR_NETWORK = 2;
240
241 /**
242 * Value of {@link #COLUMN_REASON} when the download exceeds a size limit for downloads over
243 * the mobile network and the download manager is waiting for a Wi-Fi connection to proceed.
244 */
245 public final static int PAUSED_QUEUED_FOR_WIFI = 3;
246
247 /**
248 * Value of {@link #COLUMN_REASON} when the download is paused for some other reason.
249 */
250 public final static int PAUSED_UNKNOWN = 4;
251
252 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700253 * Broadcast intent action sent by the download manager when a download completes.
254 */
255 public final static String ACTION_DOWNLOAD_COMPLETE = "android.intent.action.DOWNLOAD_COMPLETE";
256
257 /**
Steve Howard610c4352010-09-30 18:30:04 -0700258 * Broadcast intent action sent by the download manager when the user clicks on a running
259 * download, either from a system notification or from the downloads UI.
Steve Howardb8e07a52010-07-21 14:53:21 -0700260 */
261 public final static String ACTION_NOTIFICATION_CLICKED =
262 "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED";
263
264 /**
Steve Howarde78fc182010-09-24 14:59:36 -0700265 * Intent action to launch an activity to display all downloads.
266 */
267 public final static String ACTION_VIEW_DOWNLOADS = "android.intent.action.VIEW_DOWNLOADS";
268
269 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700270 * Intent extra included with {@link #ACTION_DOWNLOAD_COMPLETE} intents, indicating the ID (as a
271 * long) of the download that just completed.
272 */
273 public static final String EXTRA_DOWNLOAD_ID = "extra_download_id";
Steve Howarda2709362010-07-02 17:12:48 -0700274
Vasu Nori71b8c232010-10-27 15:22:19 -0700275 /**
276 * When clicks on multiple notifications are received, the following
277 * provides an array of download ids corresponding to the download notification that was
278 * clicked. It can be retrieved by the receiver of this
279 * Intent using {@link android.content.Intent#getLongArrayExtra(String)}.
280 */
281 public static final String EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS = "extra_click_download_ids";
282
Steve Howarda2709362010-07-02 17:12:48 -0700283 // this array must contain all public columns
284 private static final String[] COLUMNS = new String[] {
285 COLUMN_ID,
Vasu Nori216fa222010-10-12 23:08:13 -0700286 COLUMN_MEDIAPROVIDER_URI,
Steve Howarda2709362010-07-02 17:12:48 -0700287 COLUMN_TITLE,
288 COLUMN_DESCRIPTION,
289 COLUMN_URI,
290 COLUMN_MEDIA_TYPE,
291 COLUMN_TOTAL_SIZE_BYTES,
292 COLUMN_LOCAL_URI,
293 COLUMN_STATUS,
Steve Howard3e8c1d32010-09-29 17:03:32 -0700294 COLUMN_REASON,
Steve Howarda2709362010-07-02 17:12:48 -0700295 COLUMN_BYTES_DOWNLOADED_SO_FAR,
Doug Zongkeree04af32010-10-08 13:42:16 -0700296 COLUMN_LAST_MODIFIED_TIMESTAMP,
297 COLUMN_LOCAL_FILENAME
Steve Howarda2709362010-07-02 17:12:48 -0700298 };
299
300 // columns to request from DownloadProvider
301 private static final String[] UNDERLYING_COLUMNS = new String[] {
302 Downloads.Impl._ID,
Vasu Nori216fa222010-10-12 23:08:13 -0700303 Downloads.Impl.COLUMN_MEDIAPROVIDER_URI,
Vasu Norief7e33b2010-10-20 13:26:02 -0700304 Downloads.Impl.COLUMN_TITLE,
305 Downloads.Impl.COLUMN_DESCRIPTION,
306 Downloads.Impl.COLUMN_URI,
307 Downloads.Impl.COLUMN_MIME_TYPE,
308 Downloads.Impl.COLUMN_TOTAL_BYTES,
309 Downloads.Impl.COLUMN_STATUS,
310 Downloads.Impl.COLUMN_CURRENT_BYTES,
311 Downloads.Impl.COLUMN_LAST_MODIFICATION,
312 Downloads.Impl.COLUMN_DESTINATION,
Steve Howarda9e87c92010-09-16 12:02:03 -0700313 Downloads.Impl.COLUMN_FILE_NAME_HINT,
Steve Howardbb0d23b2010-09-22 18:56:29 -0700314 Downloads.Impl._DATA,
Steve Howarda2709362010-07-02 17:12:48 -0700315 };
316
317 private static final Set<String> LONG_COLUMNS = new HashSet<String>(
Steve Howard3e8c1d32010-09-29 17:03:32 -0700318 Arrays.asList(COLUMN_ID, COLUMN_TOTAL_SIZE_BYTES, COLUMN_STATUS, COLUMN_REASON,
Steve Howardadcb6972010-07-12 17:09:25 -0700319 COLUMN_BYTES_DOWNLOADED_SO_FAR, COLUMN_LAST_MODIFIED_TIMESTAMP));
Steve Howarda2709362010-07-02 17:12:48 -0700320
321 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700322 * This class contains all the information necessary to request a new download. The URI is the
Steve Howarda2709362010-07-02 17:12:48 -0700323 * only required parameter.
Steve Howard4f564cd2010-09-22 15:57:25 -0700324 *
325 * Note that the default download destination is a shared volume where the system might delete
326 * your file if it needs to reclaim space for system use. If this is a problem, use a location
327 * on external storage (see {@link #setDestinationUri(Uri)}.
Steve Howarda2709362010-07-02 17:12:48 -0700328 */
329 public static class Request {
330 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700331 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
332 * {@link ConnectivityManager#TYPE_MOBILE}.
333 */
334 public static final int NETWORK_MOBILE = 1 << 0;
Steve Howarda2709362010-07-02 17:12:48 -0700335
Steve Howardb8e07a52010-07-21 14:53:21 -0700336 /**
337 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
338 * {@link ConnectivityManager#TYPE_WIFI}.
339 */
340 public static final int NETWORK_WIFI = 1 << 1;
341
Steve Howardb8e07a52010-07-21 14:53:21 -0700342 private Uri mUri;
343 private Uri mDestinationUri;
Steve Howard4f564cd2010-09-22 15:57:25 -0700344 private List<Pair<String, String>> mRequestHeaders = new ArrayList<Pair<String, String>>();
345 private CharSequence mTitle;
346 private CharSequence mDescription;
Steve Howard4f564cd2010-09-22 15:57:25 -0700347 private String mMimeType;
Steve Howardb8e07a52010-07-21 14:53:21 -0700348 private boolean mRoamingAllowed = true;
349 private int mAllowedNetworkTypes = ~0; // default to all network types allowed
Steve Howard90fb15a2010-09-09 16:13:41 -0700350 private boolean mIsVisibleInDownloadsUi = true;
Steve Howarda2709362010-07-02 17:12:48 -0700351
352 /**
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700353 * This download is visible but only shows in the notifications
354 * while it's in progress.
355 */
356 public static final int VISIBILITY_VISIBLE = 0;
357
358 /**
359 * This download is visible and shows in the notifications while
360 * in progress and after completion.
361 */
362 public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED = 1;
363
364 /**
365 * This download doesn't show in the UI or in the notifications.
366 */
367 public static final int VISIBILITY_HIDDEN = 2;
368
369 /** can take any of the following values: {@link #VISIBILITY_HIDDEN}
370 * {@link #VISIBILITY_VISIBLE_NOTIFY_COMPLETED}, {@link #VISIBILITY_VISIBLE}
371 */
372 private int mNotificationVisibility = VISIBILITY_VISIBLE;
373
374 /**
Steve Howarda2709362010-07-02 17:12:48 -0700375 * @param uri the HTTP URI to download.
376 */
377 public Request(Uri uri) {
378 if (uri == null) {
379 throw new NullPointerException();
380 }
381 String scheme = uri.getScheme();
Paul Westbrook86a60192010-09-15 12:55:49 -0700382 if (scheme == null || (!scheme.equals("http") && !scheme.equals("https"))) {
383 throw new IllegalArgumentException("Can only download HTTP/HTTPS URIs: " + uri);
Steve Howarda2709362010-07-02 17:12:48 -0700384 }
385 mUri = uri;
386 }
387
388 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700389 * Set the local destination for the downloaded file. Must be a file URI to a path on
Steve Howarda2709362010-07-02 17:12:48 -0700390 * external storage, and the calling application must have the WRITE_EXTERNAL_STORAGE
391 * permission.
392 *
Steve Howard4f564cd2010-09-22 15:57:25 -0700393 * By default, downloads are saved to a generated filename in the shared download cache and
394 * may be deleted by the system at any time to reclaim space.
Steve Howarda2709362010-07-02 17:12:48 -0700395 *
396 * @return this object
397 */
398 public Request setDestinationUri(Uri uri) {
399 mDestinationUri = uri;
400 return this;
401 }
402
403 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700404 * Set the local destination for the downloaded file to a path within the application's
405 * external files directory (as returned by {@link Context#getExternalFilesDir(String)}.
406 *
407 * @param context the {@link Context} to use in determining the external files directory
408 * @param dirType the directory type to pass to {@link Context#getExternalFilesDir(String)}
409 * @param subPath the path within the external directory, including the destination filename
410 * @return this object
411 */
412 public Request setDestinationInExternalFilesDir(Context context, String dirType,
413 String subPath) {
414 setDestinationFromBase(context.getExternalFilesDir(dirType), subPath);
415 return this;
416 }
417
418 /**
419 * Set the local destination for the downloaded file to a path within the public external
420 * storage directory (as returned by
421 * {@link Environment#getExternalStoragePublicDirectory(String)}.
422 *
423 * @param dirType the directory type to pass to
424 * {@link Environment#getExternalStoragePublicDirectory(String)}
425 * @param subPath the path within the external directory, including the destination filename
426 * @return this object
427 */
428 public Request setDestinationInExternalPublicDir(String dirType, String subPath) {
429 setDestinationFromBase(Environment.getExternalStoragePublicDirectory(dirType), subPath);
430 return this;
431 }
432
433 private void setDestinationFromBase(File base, String subPath) {
434 if (subPath == null) {
435 throw new NullPointerException("subPath cannot be null");
436 }
437 mDestinationUri = Uri.withAppendedPath(Uri.fromFile(base), subPath);
438 }
439
440 /**
441 * Add an HTTP header to be included with the download request. The header will be added to
442 * the end of the list.
Steve Howarda2709362010-07-02 17:12:48 -0700443 * @param header HTTP header name
444 * @param value header value
445 * @return this object
Steve Howard4f564cd2010-09-22 15:57:25 -0700446 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2">HTTP/1.1
447 * Message Headers</a>
Steve Howarda2709362010-07-02 17:12:48 -0700448 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700449 public Request addRequestHeader(String header, String value) {
450 if (header == null) {
451 throw new NullPointerException("header cannot be null");
452 }
453 if (header.contains(":")) {
454 throw new IllegalArgumentException("header may not contain ':'");
455 }
456 if (value == null) {
457 value = "";
458 }
459 mRequestHeaders.add(Pair.create(header, value));
Steve Howarda2709362010-07-02 17:12:48 -0700460 return this;
461 }
462
463 /**
Steve Howard610c4352010-09-30 18:30:04 -0700464 * Set the title of this download, to be displayed in notifications (if enabled). If no
465 * title is given, a default one will be assigned based on the download filename, once the
466 * download starts.
Steve Howarda2709362010-07-02 17:12:48 -0700467 * @return this object
468 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700469 public Request setTitle(CharSequence title) {
Steve Howarda2709362010-07-02 17:12:48 -0700470 mTitle = title;
471 return this;
472 }
473
474 /**
475 * Set a description of this download, to be displayed in notifications (if enabled)
476 * @return this object
477 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700478 public Request setDescription(CharSequence description) {
Steve Howarda2709362010-07-02 17:12:48 -0700479 mDescription = description;
480 return this;
481 }
482
483 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700484 * Set the MIME content type of this download. This will override the content type declared
Steve Howarda2709362010-07-02 17:12:48 -0700485 * in the server's response.
Steve Howard4f564cd2010-09-22 15:57:25 -0700486 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7">HTTP/1.1
487 * Media Types</a>
Steve Howarda2709362010-07-02 17:12:48 -0700488 * @return this object
489 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700490 public Request setMimeType(String mimeType) {
491 mMimeType = mimeType;
Steve Howarda2709362010-07-02 17:12:48 -0700492 return this;
493 }
494
495 /**
Steve Howard8e15afe2010-07-28 17:12:40 -0700496 * Control whether a system notification is posted by the download manager while this
497 * download is running. If enabled, the download manager posts notifications about downloads
498 * through the system {@link android.app.NotificationManager}. By default, a notification is
499 * shown.
Steve Howarda2709362010-07-02 17:12:48 -0700500 *
Steve Howard8e15afe2010-07-28 17:12:40 -0700501 * If set to false, this requires the permission
502 * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
503 *
504 * @param show whether the download manager should show a notification for this download.
Steve Howarda2709362010-07-02 17:12:48 -0700505 * @return this object
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700506 * @deprecated use {@link #setNotificationVisibility(int)}
Steve Howarda2709362010-07-02 17:12:48 -0700507 */
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700508 @Deprecated
Steve Howard8e15afe2010-07-28 17:12:40 -0700509 public Request setShowRunningNotification(boolean show) {
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700510 return (show) ? setNotificationVisibility(VISIBILITY_VISIBLE) :
511 setNotificationVisibility(VISIBILITY_HIDDEN);
512 }
513
514 /**
515 * Control whether a system notification is posted by the download manager while this
516 * download is running or when it is completed.
517 * If enabled, the download manager posts notifications about downloads
518 * through the system {@link android.app.NotificationManager}.
519 * By default, a notification is shown only when the download is in progress.
520 *<p>
521 * It can take the following values: {@link #VISIBILITY_HIDDEN},
522 * {@link #VISIBILITY_VISIBLE},
523 * {@link #VISIBILITY_VISIBLE_NOTIFY_COMPLETED}.
524 *<p>
525 * If set to {@link #VISIBILITY_HIDDEN}, this requires the permission
526 * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
527 *
528 * @param visibility the visibility setting value
529 * @return this object
530 */
531 public Request setNotificationVisibility(int visibility) {
532 mNotificationVisibility = visibility;
Steve Howarda2709362010-07-02 17:12:48 -0700533 return this;
534 }
535
Steve Howardb8e07a52010-07-21 14:53:21 -0700536 /**
537 * Restrict the types of networks over which this download may proceed. By default, all
538 * network types are allowed.
539 * @param flags any combination of the NETWORK_* bit flags.
540 * @return this object
541 */
Steve Howarda2709362010-07-02 17:12:48 -0700542 public Request setAllowedNetworkTypes(int flags) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700543 mAllowedNetworkTypes = flags;
544 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700545 }
546
Steve Howardb8e07a52010-07-21 14:53:21 -0700547 /**
548 * Set whether this download may proceed over a roaming connection. By default, roaming is
549 * allowed.
550 * @param allowed whether to allow a roaming connection to be used
551 * @return this object
552 */
Steve Howarda2709362010-07-02 17:12:48 -0700553 public Request setAllowedOverRoaming(boolean allowed) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700554 mRoamingAllowed = allowed;
555 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700556 }
557
558 /**
Steve Howard90fb15a2010-09-09 16:13:41 -0700559 * Set whether this download should be displayed in the system's Downloads UI. True by
560 * default.
561 * @param isVisible whether to display this download in the Downloads UI
562 * @return this object
563 */
564 public Request setVisibleInDownloadsUi(boolean isVisible) {
565 mIsVisibleInDownloadsUi = isVisible;
566 return this;
567 }
568
569 /**
Steve Howarda2709362010-07-02 17:12:48 -0700570 * @return ContentValues to be passed to DownloadProvider.insert()
571 */
Steve Howardb8e07a52010-07-21 14:53:21 -0700572 ContentValues toContentValues(String packageName) {
Steve Howarda2709362010-07-02 17:12:48 -0700573 ContentValues values = new ContentValues();
574 assert mUri != null;
Vasu Norief7e33b2010-10-20 13:26:02 -0700575 values.put(Downloads.Impl.COLUMN_URI, mUri.toString());
Steve Howardb8e07a52010-07-21 14:53:21 -0700576 values.put(Downloads.Impl.COLUMN_IS_PUBLIC_API, true);
Vasu Norief7e33b2010-10-20 13:26:02 -0700577 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE, packageName);
Steve Howarda2709362010-07-02 17:12:48 -0700578
579 if (mDestinationUri != null) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700580 values.put(Downloads.Impl.COLUMN_DESTINATION, Downloads.Impl.DESTINATION_FILE_URI);
581 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, mDestinationUri.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700582 } else {
Vasu Norief7e33b2010-10-20 13:26:02 -0700583 values.put(Downloads.Impl.COLUMN_DESTINATION,
584 Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE);
Steve Howarda2709362010-07-02 17:12:48 -0700585 }
586
587 if (!mRequestHeaders.isEmpty()) {
Steve Howardea9147d2010-07-13 19:02:45 -0700588 encodeHttpHeaders(values);
Steve Howarda2709362010-07-02 17:12:48 -0700589 }
590
Vasu Norief7e33b2010-10-20 13:26:02 -0700591 putIfNonNull(values, Downloads.Impl.COLUMN_TITLE, mTitle);
592 putIfNonNull(values, Downloads.Impl.COLUMN_DESCRIPTION, mDescription);
593 putIfNonNull(values, Downloads.Impl.COLUMN_MIME_TYPE, mMimeType);
Steve Howarda2709362010-07-02 17:12:48 -0700594
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700595 values.put(Downloads.Impl.COLUMN_VISIBILITY, mNotificationVisibility);
Steve Howardb8e07a52010-07-21 14:53:21 -0700596 values.put(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES, mAllowedNetworkTypes);
597 values.put(Downloads.Impl.COLUMN_ALLOW_ROAMING, mRoamingAllowed);
Steve Howard90fb15a2010-09-09 16:13:41 -0700598 values.put(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, mIsVisibleInDownloadsUi);
Steve Howardb8e07a52010-07-21 14:53:21 -0700599
Steve Howarda2709362010-07-02 17:12:48 -0700600 return values;
601 }
602
Steve Howardea9147d2010-07-13 19:02:45 -0700603 private void encodeHttpHeaders(ContentValues values) {
604 int index = 0;
Steve Howard4f564cd2010-09-22 15:57:25 -0700605 for (Pair<String, String> header : mRequestHeaders) {
606 String headerString = header.first + ": " + header.second;
Steve Howardea9147d2010-07-13 19:02:45 -0700607 values.put(Downloads.Impl.RequestHeaders.INSERT_KEY_PREFIX + index, headerString);
608 index++;
609 }
610 }
611
Steve Howard4f564cd2010-09-22 15:57:25 -0700612 private void putIfNonNull(ContentValues contentValues, String key, Object value) {
Steve Howarda2709362010-07-02 17:12:48 -0700613 if (value != null) {
Steve Howard4f564cd2010-09-22 15:57:25 -0700614 contentValues.put(key, value.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700615 }
616 }
617 }
618
619 /**
620 * This class may be used to filter download manager queries.
621 */
622 public static class Query {
Steve Howardf054e192010-09-01 18:26:26 -0700623 /**
624 * Constant for use with {@link #orderBy}
625 * @hide
626 */
627 public static final int ORDER_ASCENDING = 1;
628
629 /**
630 * Constant for use with {@link #orderBy}
631 * @hide
632 */
633 public static final int ORDER_DESCENDING = 2;
634
Steve Howard64c48b82010-10-07 17:53:52 -0700635 private long[] mIds = null;
Steve Howarda2709362010-07-02 17:12:48 -0700636 private Integer mStatusFlags = null;
Vasu Norief7e33b2010-10-20 13:26:02 -0700637 private String mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
Steve Howardf054e192010-09-01 18:26:26 -0700638 private int mOrderDirection = ORDER_DESCENDING;
Steve Howard90fb15a2010-09-09 16:13:41 -0700639 private boolean mOnlyIncludeVisibleInDownloadsUi = false;
Steve Howarda2709362010-07-02 17:12:48 -0700640
641 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700642 * Include only the downloads with the given IDs.
Steve Howarda2709362010-07-02 17:12:48 -0700643 * @return this object
644 */
Steve Howard64c48b82010-10-07 17:53:52 -0700645 public Query setFilterById(long... ids) {
646 mIds = ids;
Steve Howarda2709362010-07-02 17:12:48 -0700647 return this;
648 }
649
650 /**
651 * Include only downloads with status matching any the given status flags.
652 * @param flags any combination of the STATUS_* bit flags
653 * @return this object
654 */
655 public Query setFilterByStatus(int flags) {
656 mStatusFlags = flags;
657 return this;
658 }
659
660 /**
Steve Howard90fb15a2010-09-09 16:13:41 -0700661 * Controls whether this query includes downloads not visible in the system's Downloads UI.
662 * @param value if true, this query will only include downloads that should be displayed in
663 * the system's Downloads UI; if false (the default), this query will include
664 * both visible and invisible downloads.
665 * @return this object
666 * @hide
667 */
668 public Query setOnlyIncludeVisibleInDownloadsUi(boolean value) {
669 mOnlyIncludeVisibleInDownloadsUi = value;
670 return this;
671 }
672
673 /**
Steve Howardf054e192010-09-01 18:26:26 -0700674 * Change the sort order of the returned Cursor.
675 *
676 * @param column one of the COLUMN_* constants; currently, only
677 * {@link #COLUMN_LAST_MODIFIED_TIMESTAMP} and {@link #COLUMN_TOTAL_SIZE_BYTES} are
678 * supported.
679 * @param direction either {@link #ORDER_ASCENDING} or {@link #ORDER_DESCENDING}
680 * @return this object
681 * @hide
682 */
683 public Query orderBy(String column, int direction) {
684 if (direction != ORDER_ASCENDING && direction != ORDER_DESCENDING) {
685 throw new IllegalArgumentException("Invalid direction: " + direction);
686 }
687
688 if (column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP)) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700689 mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
Steve Howardf054e192010-09-01 18:26:26 -0700690 } else if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700691 mOrderByColumn = Downloads.Impl.COLUMN_TOTAL_BYTES;
Steve Howardf054e192010-09-01 18:26:26 -0700692 } else {
693 throw new IllegalArgumentException("Cannot order by " + column);
694 }
695 mOrderDirection = direction;
696 return this;
697 }
698
699 /**
Steve Howarda2709362010-07-02 17:12:48 -0700700 * Run this query using the given ContentResolver.
701 * @param projection the projection to pass to ContentResolver.query()
702 * @return the Cursor returned by ContentResolver.query()
703 */
Steve Howardeca77fc2010-09-12 18:49:08 -0700704 Cursor runQuery(ContentResolver resolver, String[] projection, Uri baseUri) {
705 Uri uri = baseUri;
Steve Howard90fb15a2010-09-09 16:13:41 -0700706 List<String> selectionParts = new ArrayList<String>();
Steve Howard64c48b82010-10-07 17:53:52 -0700707 String[] selectionArgs = null;
Steve Howarda2709362010-07-02 17:12:48 -0700708
Steve Howard64c48b82010-10-07 17:53:52 -0700709 if (mIds != null) {
710 selectionParts.add(getWhereClauseForIds(mIds));
711 selectionArgs = getWhereArgsForIds(mIds);
Steve Howarda2709362010-07-02 17:12:48 -0700712 }
713
714 if (mStatusFlags != null) {
715 List<String> parts = new ArrayList<String>();
716 if ((mStatusFlags & STATUS_PENDING) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700717 parts.add(statusClause("=", Downloads.Impl.STATUS_PENDING));
Steve Howarda2709362010-07-02 17:12:48 -0700718 }
719 if ((mStatusFlags & STATUS_RUNNING) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700720 parts.add(statusClause("=", Downloads.Impl.STATUS_RUNNING));
Steve Howarda2709362010-07-02 17:12:48 -0700721 }
722 if ((mStatusFlags & STATUS_PAUSED) != 0) {
Steve Howard3e8c1d32010-09-29 17:03:32 -0700723 parts.add(statusClause("=", Downloads.Impl.STATUS_PAUSED_BY_APP));
724 parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_TO_RETRY));
725 parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_FOR_NETWORK));
726 parts.add(statusClause("=", Downloads.Impl.STATUS_QUEUED_FOR_WIFI));
Steve Howarda2709362010-07-02 17:12:48 -0700727 }
728 if ((mStatusFlags & STATUS_SUCCESSFUL) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700729 parts.add(statusClause("=", Downloads.Impl.STATUS_SUCCESS));
Steve Howarda2709362010-07-02 17:12:48 -0700730 }
731 if ((mStatusFlags & STATUS_FAILED) != 0) {
732 parts.add("(" + statusClause(">=", 400)
733 + " AND " + statusClause("<", 600) + ")");
734 }
Steve Howard90fb15a2010-09-09 16:13:41 -0700735 selectionParts.add(joinStrings(" OR ", parts));
Steve Howarda2709362010-07-02 17:12:48 -0700736 }
Steve Howardf054e192010-09-01 18:26:26 -0700737
Steve Howard90fb15a2010-09-09 16:13:41 -0700738 if (mOnlyIncludeVisibleInDownloadsUi) {
739 selectionParts.add(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI + " != '0'");
740 }
741
Vasu Nori216fa222010-10-12 23:08:13 -0700742 // only return rows which are not marked 'deleted = 1'
743 selectionParts.add(Downloads.Impl.COLUMN_DELETED + " != '1'");
744
Steve Howard90fb15a2010-09-09 16:13:41 -0700745 String selection = joinStrings(" AND ", selectionParts);
Steve Howardf054e192010-09-01 18:26:26 -0700746 String orderDirection = (mOrderDirection == ORDER_ASCENDING ? "ASC" : "DESC");
747 String orderBy = mOrderByColumn + " " + orderDirection;
748
Steve Howard64c48b82010-10-07 17:53:52 -0700749 return resolver.query(uri, projection, selection, selectionArgs, orderBy);
Steve Howarda2709362010-07-02 17:12:48 -0700750 }
751
752 private String joinStrings(String joiner, Iterable<String> parts) {
753 StringBuilder builder = new StringBuilder();
754 boolean first = true;
755 for (String part : parts) {
756 if (!first) {
757 builder.append(joiner);
758 }
759 builder.append(part);
760 first = false;
761 }
762 return builder.toString();
763 }
764
765 private String statusClause(String operator, int value) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700766 return Downloads.Impl.COLUMN_STATUS + operator + "'" + value + "'";
Steve Howarda2709362010-07-02 17:12:48 -0700767 }
768 }
769
770 private ContentResolver mResolver;
Steve Howardb8e07a52010-07-21 14:53:21 -0700771 private String mPackageName;
Steve Howardeca77fc2010-09-12 18:49:08 -0700772 private Uri mBaseUri = Downloads.Impl.CONTENT_URI;
Steve Howarda2709362010-07-02 17:12:48 -0700773
774 /**
775 * @hide
776 */
Steve Howardb8e07a52010-07-21 14:53:21 -0700777 public DownloadManager(ContentResolver resolver, String packageName) {
Steve Howarda2709362010-07-02 17:12:48 -0700778 mResolver = resolver;
Steve Howardb8e07a52010-07-21 14:53:21 -0700779 mPackageName = packageName;
Steve Howarda2709362010-07-02 17:12:48 -0700780 }
781
782 /**
Steve Howardeca77fc2010-09-12 18:49:08 -0700783 * Makes this object access the download provider through /all_downloads URIs rather than
784 * /my_downloads URIs, for clients that have permission to do so.
785 * @hide
786 */
787 public void setAccessAllDownloads(boolean accessAllDownloads) {
788 if (accessAllDownloads) {
789 mBaseUri = Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI;
790 } else {
791 mBaseUri = Downloads.Impl.CONTENT_URI;
792 }
793 }
794
795 /**
Steve Howarda2709362010-07-02 17:12:48 -0700796 * Enqueue a new download. The download will start automatically once the download manager is
797 * ready to execute it and connectivity is available.
798 *
799 * @param request the parameters specifying this download
800 * @return an ID for the download, unique across the system. This ID is used to make future
801 * calls related to this download.
802 */
803 public long enqueue(Request request) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700804 ContentValues values = request.toContentValues(mPackageName);
Vasu Norief7e33b2010-10-20 13:26:02 -0700805 Uri downloadUri = mResolver.insert(Downloads.Impl.CONTENT_URI, values);
Steve Howarda2709362010-07-02 17:12:48 -0700806 long id = Long.parseLong(downloadUri.getLastPathSegment());
807 return id;
808 }
809
810 /**
Vasu Nori216fa222010-10-12 23:08:13 -0700811 * Marks the specified download as 'to be deleted'. This is done when a completed download
812 * is to be removed but the row was stored without enough info to delete the corresponding
813 * metadata from Mediaprovider database. Actual cleanup of this row is done in DownloadService.
814 *
815 * @param ids the IDs of the downloads to be marked 'deleted'
816 * @return the number of downloads actually updated
817 * @hide
818 */
819 public int markRowDeleted(long... ids) {
820 if (ids == null || ids.length == 0) {
821 // called with nothing to remove!
822 throw new IllegalArgumentException("input param 'ids' can't be null");
823 }
824 ContentValues values = new ContentValues();
825 values.put(Downloads.Impl.COLUMN_DELETED, 1);
826 return mResolver.update(mBaseUri, values, getWhereClauseForIds(ids),
827 getWhereArgsForIds(ids));
828 }
829
830 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700831 * Cancel downloads and remove them from the download manager. Each download will be stopped if
Steve Howarda2709362010-07-02 17:12:48 -0700832 * it was running, and it will no longer be accessible through the download manager. If a file
Steve Howard64c48b82010-10-07 17:53:52 -0700833 * was already downloaded to external storage, it will not be deleted.
Steve Howarda2709362010-07-02 17:12:48 -0700834 *
Steve Howard64c48b82010-10-07 17:53:52 -0700835 * @param ids the IDs of the downloads to remove
836 * @return the number of downloads actually removed
Steve Howarda2709362010-07-02 17:12:48 -0700837 */
Steve Howard64c48b82010-10-07 17:53:52 -0700838 public int remove(long... ids) {
Vasu Norie7be6bd2010-10-10 14:58:08 -0700839 if (ids == null || ids.length == 0) {
840 // called with nothing to remove!
841 throw new IllegalArgumentException("input param 'ids' can't be null");
Steve Howarda2709362010-07-02 17:12:48 -0700842 }
Vasu Norie7be6bd2010-10-10 14:58:08 -0700843 return mResolver.delete(mBaseUri, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
Steve Howarda2709362010-07-02 17:12:48 -0700844 }
845
846 /**
847 * Query the download manager about downloads that have been requested.
848 * @param query parameters specifying filters for this query
849 * @return a Cursor over the result set of downloads, with columns consisting of all the
850 * COLUMN_* constants.
851 */
852 public Cursor query(Query query) {
Steve Howardeca77fc2010-09-12 18:49:08 -0700853 Cursor underlyingCursor = query.runQuery(mResolver, UNDERLYING_COLUMNS, mBaseUri);
Steve Howardf054e192010-09-01 18:26:26 -0700854 if (underlyingCursor == null) {
855 return null;
856 }
Steve Howardeca77fc2010-09-12 18:49:08 -0700857 return new CursorTranslator(underlyingCursor, mBaseUri);
Steve Howarda2709362010-07-02 17:12:48 -0700858 }
859
860 /**
861 * Open a downloaded file for reading. The download must have completed.
862 * @param id the ID of the download
863 * @return a read-only {@link ParcelFileDescriptor}
864 * @throws FileNotFoundException if the destination file does not already exist
865 */
866 public ParcelFileDescriptor openDownloadedFile(long id) throws FileNotFoundException {
867 return mResolver.openFileDescriptor(getDownloadUri(id), "r");
868 }
869
870 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700871 * Restart the given downloads, which must have already completed (successfully or not). This
Steve Howard90fb15a2010-09-09 16:13:41 -0700872 * method will only work when called from within the download manager's process.
Steve Howard64c48b82010-10-07 17:53:52 -0700873 * @param ids the IDs of the downloads
Steve Howard90fb15a2010-09-09 16:13:41 -0700874 * @hide
875 */
Steve Howard64c48b82010-10-07 17:53:52 -0700876 public void restartDownload(long... ids) {
877 Cursor cursor = query(new Query().setFilterById(ids));
Steve Howard90fb15a2010-09-09 16:13:41 -0700878 try {
Steve Howard64c48b82010-10-07 17:53:52 -0700879 for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
880 int status = cursor.getInt(cursor.getColumnIndex(COLUMN_STATUS));
881 if (status != STATUS_SUCCESSFUL && status != STATUS_FAILED) {
882 throw new IllegalArgumentException("Cannot restart incomplete download: "
883 + cursor.getLong(cursor.getColumnIndex(COLUMN_ID)));
884 }
Steve Howard90fb15a2010-09-09 16:13:41 -0700885 }
886 } finally {
887 cursor.close();
888 }
889
890 ContentValues values = new ContentValues();
891 values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, 0);
892 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, -1);
893 values.putNull(Downloads.Impl._DATA);
894 values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING);
Steve Howard64c48b82010-10-07 17:53:52 -0700895 mResolver.update(mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
Steve Howard90fb15a2010-09-09 16:13:41 -0700896 }
897
898 /**
Steve Howarda2709362010-07-02 17:12:48 -0700899 * Get the DownloadProvider URI for the download with the given ID.
900 */
Steve Howardeca77fc2010-09-12 18:49:08 -0700901 Uri getDownloadUri(long id) {
902 return ContentUris.withAppendedId(mBaseUri, id);
Steve Howarda2709362010-07-02 17:12:48 -0700903 }
904
905 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700906 * Get a parameterized SQL WHERE clause to select a bunch of IDs.
907 */
908 static String getWhereClauseForIds(long[] ids) {
909 StringBuilder whereClause = new StringBuilder();
Vasu Norie7be6bd2010-10-10 14:58:08 -0700910 whereClause.append("(");
Steve Howard64c48b82010-10-07 17:53:52 -0700911 for (int i = 0; i < ids.length; i++) {
912 if (i > 0) {
Vasu Norie7be6bd2010-10-10 14:58:08 -0700913 whereClause.append("OR ");
Steve Howard64c48b82010-10-07 17:53:52 -0700914 }
Vasu Norie7be6bd2010-10-10 14:58:08 -0700915 whereClause.append(Downloads.Impl._ID);
916 whereClause.append(" = ? ");
Steve Howard64c48b82010-10-07 17:53:52 -0700917 }
918 whereClause.append(")");
919 return whereClause.toString();
920 }
921
922 /**
923 * Get the selection args for a clause returned by {@link #getWhereClauseForIds(long[])}.
924 */
925 static String[] getWhereArgsForIds(long[] ids) {
926 String[] whereArgs = new String[ids.length];
927 for (int i = 0; i < ids.length; i++) {
928 whereArgs[i] = Long.toString(ids[i]);
929 }
930 return whereArgs;
931 }
932
933 /**
Steve Howarda2709362010-07-02 17:12:48 -0700934 * This class wraps a cursor returned by DownloadProvider -- the "underlying cursor" -- and
935 * presents a different set of columns, those defined in the DownloadManager.COLUMN_* constants.
936 * Some columns correspond directly to underlying values while others are computed from
937 * underlying data.
938 */
939 private static class CursorTranslator extends CursorWrapper {
Steve Howardeca77fc2010-09-12 18:49:08 -0700940 private Uri mBaseUri;
941
942 public CursorTranslator(Cursor cursor, Uri baseUri) {
Steve Howarda2709362010-07-02 17:12:48 -0700943 super(cursor);
Steve Howardeca77fc2010-09-12 18:49:08 -0700944 mBaseUri = baseUri;
Steve Howarda2709362010-07-02 17:12:48 -0700945 }
946
947 @Override
948 public int getColumnIndex(String columnName) {
949 return Arrays.asList(COLUMNS).indexOf(columnName);
950 }
951
952 @Override
953 public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException {
954 int index = getColumnIndex(columnName);
955 if (index == -1) {
Steve Howardf054e192010-09-01 18:26:26 -0700956 throw new IllegalArgumentException("No such column: " + columnName);
Steve Howarda2709362010-07-02 17:12:48 -0700957 }
958 return index;
959 }
960
961 @Override
962 public String getColumnName(int columnIndex) {
963 int numColumns = COLUMNS.length;
964 if (columnIndex < 0 || columnIndex >= numColumns) {
965 throw new IllegalArgumentException("Invalid column index " + columnIndex + ", "
966 + numColumns + " columns exist");
967 }
968 return COLUMNS[columnIndex];
969 }
970
971 @Override
972 public String[] getColumnNames() {
973 String[] returnColumns = new String[COLUMNS.length];
974 System.arraycopy(COLUMNS, 0, returnColumns, 0, COLUMNS.length);
975 return returnColumns;
976 }
977
978 @Override
979 public int getColumnCount() {
980 return COLUMNS.length;
981 }
982
983 @Override
984 public byte[] getBlob(int columnIndex) {
985 throw new UnsupportedOperationException();
986 }
987
988 @Override
989 public double getDouble(int columnIndex) {
990 return getLong(columnIndex);
991 }
992
993 private boolean isLongColumn(String column) {
994 return LONG_COLUMNS.contains(column);
995 }
996
997 @Override
998 public float getFloat(int columnIndex) {
999 return (float) getDouble(columnIndex);
1000 }
1001
1002 @Override
1003 public int getInt(int columnIndex) {
1004 return (int) getLong(columnIndex);
1005 }
1006
1007 @Override
1008 public long getLong(int columnIndex) {
1009 return translateLong(getColumnName(columnIndex));
1010 }
1011
1012 @Override
1013 public short getShort(int columnIndex) {
1014 return (short) getLong(columnIndex);
1015 }
1016
1017 @Override
1018 public String getString(int columnIndex) {
1019 return translateString(getColumnName(columnIndex));
1020 }
1021
1022 private String translateString(String column) {
1023 if (isLongColumn(column)) {
1024 return Long.toString(translateLong(column));
1025 }
1026 if (column.equals(COLUMN_TITLE)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001027 return getUnderlyingString(Downloads.Impl.COLUMN_TITLE);
Steve Howarda2709362010-07-02 17:12:48 -07001028 }
1029 if (column.equals(COLUMN_DESCRIPTION)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001030 return getUnderlyingString(Downloads.Impl.COLUMN_DESCRIPTION);
Steve Howarda2709362010-07-02 17:12:48 -07001031 }
1032 if (column.equals(COLUMN_URI)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001033 return getUnderlyingString(Downloads.Impl.COLUMN_URI);
Steve Howarda2709362010-07-02 17:12:48 -07001034 }
1035 if (column.equals(COLUMN_MEDIA_TYPE)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001036 return getUnderlyingString(Downloads.Impl.COLUMN_MIME_TYPE);
Steve Howarda2709362010-07-02 17:12:48 -07001037 }
Doug Zongkeree04af32010-10-08 13:42:16 -07001038 if (column.equals(COLUMN_LOCAL_FILENAME)) {
1039 return getUnderlyingString(Downloads.Impl._DATA);
1040 }
Vasu Nori216fa222010-10-12 23:08:13 -07001041 if (column.equals(COLUMN_MEDIAPROVIDER_URI)) {
1042 return getUnderlyingString(Downloads.Impl.COLUMN_MEDIAPROVIDER_URI);
1043 }
Steve Howard8651bd52010-08-03 12:35:32 -07001044
Steve Howarda2709362010-07-02 17:12:48 -07001045 assert column.equals(COLUMN_LOCAL_URI);
Steve Howardeca77fc2010-09-12 18:49:08 -07001046 return getLocalUri();
1047 }
1048
1049 private String getLocalUri() {
Steve Howardeca77fc2010-09-12 18:49:08 -07001050 long destinationType = getUnderlyingLong(Downloads.Impl.COLUMN_DESTINATION);
1051 if (destinationType == Downloads.Impl.DESTINATION_FILE_URI) {
Steve Howarda9e87c92010-09-16 12:02:03 -07001052 // return client-provided file URI for external download
1053 return getUnderlyingString(Downloads.Impl.COLUMN_FILE_NAME_HINT);
Steve Howardeca77fc2010-09-12 18:49:08 -07001054 }
1055
Steve Howardbb0d23b2010-09-22 18:56:29 -07001056 if (destinationType == Downloads.Impl.DESTINATION_EXTERNAL) {
1057 // return stored destination for legacy external download
Steve Howard99047d72010-09-29 17:41:37 -07001058 String localPath = getUnderlyingString(Downloads.Impl._DATA);
1059 if (localPath == null) {
1060 return null;
1061 }
1062 return Uri.fromFile(new File(localPath)).toString();
Steve Howardbb0d23b2010-09-22 18:56:29 -07001063 }
1064
Steve Howardeca77fc2010-09-12 18:49:08 -07001065 // return content URI for cache download
1066 long downloadId = getUnderlyingLong(Downloads.Impl._ID);
1067 return ContentUris.withAppendedId(mBaseUri, downloadId).toString();
Steve Howarda2709362010-07-02 17:12:48 -07001068 }
1069
1070 private long translateLong(String column) {
1071 if (!isLongColumn(column)) {
1072 // mimic behavior of underlying cursor -- most likely, throw NumberFormatException
1073 return Long.valueOf(translateString(column));
1074 }
1075
1076 if (column.equals(COLUMN_ID)) {
1077 return getUnderlyingLong(Downloads.Impl._ID);
1078 }
1079 if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001080 return getUnderlyingLong(Downloads.Impl.COLUMN_TOTAL_BYTES);
Steve Howarda2709362010-07-02 17:12:48 -07001081 }
1082 if (column.equals(COLUMN_STATUS)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001083 return translateStatus((int) getUnderlyingLong(Downloads.Impl.COLUMN_STATUS));
Steve Howarda2709362010-07-02 17:12:48 -07001084 }
Steve Howard3e8c1d32010-09-29 17:03:32 -07001085 if (column.equals(COLUMN_REASON)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001086 return getReason((int) getUnderlyingLong(Downloads.Impl.COLUMN_STATUS));
Steve Howarda2709362010-07-02 17:12:48 -07001087 }
1088 if (column.equals(COLUMN_BYTES_DOWNLOADED_SO_FAR)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001089 return getUnderlyingLong(Downloads.Impl.COLUMN_CURRENT_BYTES);
Steve Howarda2709362010-07-02 17:12:48 -07001090 }
Steve Howardadcb6972010-07-12 17:09:25 -07001091 assert column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP);
Vasu Norief7e33b2010-10-20 13:26:02 -07001092 return getUnderlyingLong(Downloads.Impl.COLUMN_LAST_MODIFICATION);
Steve Howarda2709362010-07-02 17:12:48 -07001093 }
1094
Steve Howard3e8c1d32010-09-29 17:03:32 -07001095 private long getReason(int status) {
1096 switch (translateStatus(status)) {
1097 case STATUS_FAILED:
1098 return getErrorCode(status);
1099
1100 case STATUS_PAUSED:
1101 return getPausedReason(status);
1102
1103 default:
1104 return 0; // arbitrary value when status is not an error
Steve Howarda2709362010-07-02 17:12:48 -07001105 }
Steve Howard3e8c1d32010-09-29 17:03:32 -07001106 }
1107
1108 private long getPausedReason(int status) {
1109 switch (status) {
1110 case Downloads.Impl.STATUS_WAITING_TO_RETRY:
1111 return PAUSED_WAITING_TO_RETRY;
1112
1113 case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
1114 return PAUSED_WAITING_FOR_NETWORK;
1115
1116 case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
1117 return PAUSED_QUEUED_FOR_WIFI;
1118
1119 default:
1120 return PAUSED_UNKNOWN;
1121 }
1122 }
1123
1124 private long getErrorCode(int status) {
Steve Howard33bbd122010-08-02 17:51:29 -07001125 if ((400 <= status && status < Downloads.Impl.MIN_ARTIFICIAL_ERROR_STATUS)
1126 || (500 <= status && status < 600)) {
Steve Howarda2709362010-07-02 17:12:48 -07001127 // HTTP status code
1128 return status;
1129 }
1130
1131 switch (status) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001132 case Downloads.Impl.STATUS_FILE_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001133 return ERROR_FILE_ERROR;
1134
Vasu Norief7e33b2010-10-20 13:26:02 -07001135 case Downloads.Impl.STATUS_UNHANDLED_HTTP_CODE:
1136 case Downloads.Impl.STATUS_UNHANDLED_REDIRECT:
Steve Howarda2709362010-07-02 17:12:48 -07001137 return ERROR_UNHANDLED_HTTP_CODE;
1138
Vasu Norief7e33b2010-10-20 13:26:02 -07001139 case Downloads.Impl.STATUS_HTTP_DATA_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001140 return ERROR_HTTP_DATA_ERROR;
1141
Vasu Norief7e33b2010-10-20 13:26:02 -07001142 case Downloads.Impl.STATUS_TOO_MANY_REDIRECTS:
Steve Howarda2709362010-07-02 17:12:48 -07001143 return ERROR_TOO_MANY_REDIRECTS;
1144
Vasu Norief7e33b2010-10-20 13:26:02 -07001145 case Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001146 return ERROR_INSUFFICIENT_SPACE;
1147
Vasu Norief7e33b2010-10-20 13:26:02 -07001148 case Downloads.Impl.STATUS_DEVICE_NOT_FOUND_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001149 return ERROR_DEVICE_NOT_FOUND;
1150
Steve Howard33bbd122010-08-02 17:51:29 -07001151 case Downloads.Impl.STATUS_CANNOT_RESUME:
1152 return ERROR_CANNOT_RESUME;
1153
Steve Howarda9e87c92010-09-16 12:02:03 -07001154 case Downloads.Impl.STATUS_FILE_ALREADY_EXISTS_ERROR:
1155 return ERROR_FILE_ALREADY_EXISTS;
1156
Steve Howarda2709362010-07-02 17:12:48 -07001157 default:
1158 return ERROR_UNKNOWN;
1159 }
1160 }
1161
1162 private long getUnderlyingLong(String column) {
1163 return super.getLong(super.getColumnIndex(column));
1164 }
1165
1166 private String getUnderlyingString(String column) {
1167 return super.getString(super.getColumnIndex(column));
1168 }
1169
Steve Howard3e8c1d32010-09-29 17:03:32 -07001170 private int translateStatus(int status) {
Steve Howarda2709362010-07-02 17:12:48 -07001171 switch (status) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001172 case Downloads.Impl.STATUS_PENDING:
Steve Howarda2709362010-07-02 17:12:48 -07001173 return STATUS_PENDING;
1174
Vasu Norief7e33b2010-10-20 13:26:02 -07001175 case Downloads.Impl.STATUS_RUNNING:
Steve Howarda2709362010-07-02 17:12:48 -07001176 return STATUS_RUNNING;
1177
Steve Howard3e8c1d32010-09-29 17:03:32 -07001178 case Downloads.Impl.STATUS_PAUSED_BY_APP:
1179 case Downloads.Impl.STATUS_WAITING_TO_RETRY:
1180 case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
1181 case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
Steve Howarda2709362010-07-02 17:12:48 -07001182 return STATUS_PAUSED;
1183
Vasu Norief7e33b2010-10-20 13:26:02 -07001184 case Downloads.Impl.STATUS_SUCCESS:
Steve Howarda2709362010-07-02 17:12:48 -07001185 return STATUS_SUCCESSFUL;
1186
1187 default:
Vasu Norief7e33b2010-10-20 13:26:02 -07001188 assert Downloads.Impl.isStatusError(status);
Steve Howarda2709362010-07-02 17:12:48 -07001189 return STATUS_FAILED;
1190 }
1191 }
1192 }
1193}