blob: 570e49471ca878774a1f393f9dab1654cc78a2b9 [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
275 // this array must contain all public columns
276 private static final String[] COLUMNS = new String[] {
277 COLUMN_ID,
Vasu Nori216fa222010-10-12 23:08:13 -0700278 COLUMN_MEDIAPROVIDER_URI,
Steve Howarda2709362010-07-02 17:12:48 -0700279 COLUMN_TITLE,
280 COLUMN_DESCRIPTION,
281 COLUMN_URI,
282 COLUMN_MEDIA_TYPE,
283 COLUMN_TOTAL_SIZE_BYTES,
284 COLUMN_LOCAL_URI,
285 COLUMN_STATUS,
Steve Howard3e8c1d32010-09-29 17:03:32 -0700286 COLUMN_REASON,
Steve Howarda2709362010-07-02 17:12:48 -0700287 COLUMN_BYTES_DOWNLOADED_SO_FAR,
Doug Zongkeree04af32010-10-08 13:42:16 -0700288 COLUMN_LAST_MODIFIED_TIMESTAMP,
289 COLUMN_LOCAL_FILENAME
Steve Howarda2709362010-07-02 17:12:48 -0700290 };
291
292 // columns to request from DownloadProvider
293 private static final String[] UNDERLYING_COLUMNS = new String[] {
294 Downloads.Impl._ID,
Vasu Nori216fa222010-10-12 23:08:13 -0700295 Downloads.Impl.COLUMN_MEDIAPROVIDER_URI,
Vasu Norief7e33b2010-10-20 13:26:02 -0700296 Downloads.Impl.COLUMN_TITLE,
297 Downloads.Impl.COLUMN_DESCRIPTION,
298 Downloads.Impl.COLUMN_URI,
299 Downloads.Impl.COLUMN_MIME_TYPE,
300 Downloads.Impl.COLUMN_TOTAL_BYTES,
301 Downloads.Impl.COLUMN_STATUS,
302 Downloads.Impl.COLUMN_CURRENT_BYTES,
303 Downloads.Impl.COLUMN_LAST_MODIFICATION,
304 Downloads.Impl.COLUMN_DESTINATION,
Steve Howarda9e87c92010-09-16 12:02:03 -0700305 Downloads.Impl.COLUMN_FILE_NAME_HINT,
Steve Howardbb0d23b2010-09-22 18:56:29 -0700306 Downloads.Impl._DATA,
Steve Howarda2709362010-07-02 17:12:48 -0700307 };
308
309 private static final Set<String> LONG_COLUMNS = new HashSet<String>(
Steve Howard3e8c1d32010-09-29 17:03:32 -0700310 Arrays.asList(COLUMN_ID, COLUMN_TOTAL_SIZE_BYTES, COLUMN_STATUS, COLUMN_REASON,
Steve Howardadcb6972010-07-12 17:09:25 -0700311 COLUMN_BYTES_DOWNLOADED_SO_FAR, COLUMN_LAST_MODIFIED_TIMESTAMP));
Steve Howarda2709362010-07-02 17:12:48 -0700312
313 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700314 * This class contains all the information necessary to request a new download. The URI is the
Steve Howarda2709362010-07-02 17:12:48 -0700315 * only required parameter.
Steve Howard4f564cd2010-09-22 15:57:25 -0700316 *
317 * Note that the default download destination is a shared volume where the system might delete
318 * your file if it needs to reclaim space for system use. If this is a problem, use a location
319 * on external storage (see {@link #setDestinationUri(Uri)}.
Steve Howarda2709362010-07-02 17:12:48 -0700320 */
321 public static class Request {
322 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700323 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
324 * {@link ConnectivityManager#TYPE_MOBILE}.
325 */
326 public static final int NETWORK_MOBILE = 1 << 0;
Steve Howarda2709362010-07-02 17:12:48 -0700327
Steve Howardb8e07a52010-07-21 14:53:21 -0700328 /**
329 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
330 * {@link ConnectivityManager#TYPE_WIFI}.
331 */
332 public static final int NETWORK_WIFI = 1 << 1;
333
Steve Howardb8e07a52010-07-21 14:53:21 -0700334 private Uri mUri;
335 private Uri mDestinationUri;
Steve Howard4f564cd2010-09-22 15:57:25 -0700336 private List<Pair<String, String>> mRequestHeaders = new ArrayList<Pair<String, String>>();
337 private CharSequence mTitle;
338 private CharSequence mDescription;
Steve Howard4f564cd2010-09-22 15:57:25 -0700339 private String mMimeType;
Steve Howardb8e07a52010-07-21 14:53:21 -0700340 private boolean mRoamingAllowed = true;
341 private int mAllowedNetworkTypes = ~0; // default to all network types allowed
Steve Howard90fb15a2010-09-09 16:13:41 -0700342 private boolean mIsVisibleInDownloadsUi = true;
Steve Howarda2709362010-07-02 17:12:48 -0700343
344 /**
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700345 * This download is visible but only shows in the notifications
346 * while it's in progress.
347 */
348 public static final int VISIBILITY_VISIBLE = 0;
349
350 /**
351 * This download is visible and shows in the notifications while
352 * in progress and after completion.
353 */
354 public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED = 1;
355
356 /**
357 * This download doesn't show in the UI or in the notifications.
358 */
359 public static final int VISIBILITY_HIDDEN = 2;
360
361 /** can take any of the following values: {@link #VISIBILITY_HIDDEN}
362 * {@link #VISIBILITY_VISIBLE_NOTIFY_COMPLETED}, {@link #VISIBILITY_VISIBLE}
363 */
364 private int mNotificationVisibility = VISIBILITY_VISIBLE;
365
366 /**
Steve Howarda2709362010-07-02 17:12:48 -0700367 * @param uri the HTTP URI to download.
368 */
369 public Request(Uri uri) {
370 if (uri == null) {
371 throw new NullPointerException();
372 }
373 String scheme = uri.getScheme();
Paul Westbrook86a60192010-09-15 12:55:49 -0700374 if (scheme == null || (!scheme.equals("http") && !scheme.equals("https"))) {
375 throw new IllegalArgumentException("Can only download HTTP/HTTPS URIs: " + uri);
Steve Howarda2709362010-07-02 17:12:48 -0700376 }
377 mUri = uri;
378 }
379
380 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700381 * Set the local destination for the downloaded file. Must be a file URI to a path on
Steve Howarda2709362010-07-02 17:12:48 -0700382 * external storage, and the calling application must have the WRITE_EXTERNAL_STORAGE
383 * permission.
384 *
Steve Howard4f564cd2010-09-22 15:57:25 -0700385 * By default, downloads are saved to a generated filename in the shared download cache and
386 * may be deleted by the system at any time to reclaim space.
Steve Howarda2709362010-07-02 17:12:48 -0700387 *
388 * @return this object
389 */
390 public Request setDestinationUri(Uri uri) {
391 mDestinationUri = uri;
392 return this;
393 }
394
395 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700396 * Set the local destination for the downloaded file to a path within the application's
397 * external files directory (as returned by {@link Context#getExternalFilesDir(String)}.
398 *
399 * @param context the {@link Context} to use in determining the external files directory
400 * @param dirType the directory type to pass to {@link Context#getExternalFilesDir(String)}
401 * @param subPath the path within the external directory, including the destination filename
402 * @return this object
403 */
404 public Request setDestinationInExternalFilesDir(Context context, String dirType,
405 String subPath) {
406 setDestinationFromBase(context.getExternalFilesDir(dirType), subPath);
407 return this;
408 }
409
410 /**
411 * Set the local destination for the downloaded file to a path within the public external
412 * storage directory (as returned by
413 * {@link Environment#getExternalStoragePublicDirectory(String)}.
414 *
415 * @param dirType the directory type to pass to
416 * {@link Environment#getExternalStoragePublicDirectory(String)}
417 * @param subPath the path within the external directory, including the destination filename
418 * @return this object
419 */
420 public Request setDestinationInExternalPublicDir(String dirType, String subPath) {
421 setDestinationFromBase(Environment.getExternalStoragePublicDirectory(dirType), subPath);
422 return this;
423 }
424
425 private void setDestinationFromBase(File base, String subPath) {
426 if (subPath == null) {
427 throw new NullPointerException("subPath cannot be null");
428 }
429 mDestinationUri = Uri.withAppendedPath(Uri.fromFile(base), subPath);
430 }
431
432 /**
433 * Add an HTTP header to be included with the download request. The header will be added to
434 * the end of the list.
Steve Howarda2709362010-07-02 17:12:48 -0700435 * @param header HTTP header name
436 * @param value header value
437 * @return this object
Steve Howard4f564cd2010-09-22 15:57:25 -0700438 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2">HTTP/1.1
439 * Message Headers</a>
Steve Howarda2709362010-07-02 17:12:48 -0700440 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700441 public Request addRequestHeader(String header, String value) {
442 if (header == null) {
443 throw new NullPointerException("header cannot be null");
444 }
445 if (header.contains(":")) {
446 throw new IllegalArgumentException("header may not contain ':'");
447 }
448 if (value == null) {
449 value = "";
450 }
451 mRequestHeaders.add(Pair.create(header, value));
Steve Howarda2709362010-07-02 17:12:48 -0700452 return this;
453 }
454
455 /**
Steve Howard610c4352010-09-30 18:30:04 -0700456 * Set the title of this download, to be displayed in notifications (if enabled). If no
457 * title is given, a default one will be assigned based on the download filename, once the
458 * download starts.
Steve Howarda2709362010-07-02 17:12:48 -0700459 * @return this object
460 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700461 public Request setTitle(CharSequence title) {
Steve Howarda2709362010-07-02 17:12:48 -0700462 mTitle = title;
463 return this;
464 }
465
466 /**
467 * Set a description of this download, to be displayed in notifications (if enabled)
468 * @return this object
469 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700470 public Request setDescription(CharSequence description) {
Steve Howarda2709362010-07-02 17:12:48 -0700471 mDescription = description;
472 return this;
473 }
474
475 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700476 * Set the MIME content type of this download. This will override the content type declared
Steve Howarda2709362010-07-02 17:12:48 -0700477 * in the server's response.
Steve Howard4f564cd2010-09-22 15:57:25 -0700478 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7">HTTP/1.1
479 * Media Types</a>
Steve Howarda2709362010-07-02 17:12:48 -0700480 * @return this object
481 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700482 public Request setMimeType(String mimeType) {
483 mMimeType = mimeType;
Steve Howarda2709362010-07-02 17:12:48 -0700484 return this;
485 }
486
487 /**
Steve Howard8e15afe2010-07-28 17:12:40 -0700488 * Control whether a system notification is posted by the download manager while this
489 * download is running. If enabled, the download manager posts notifications about downloads
490 * through the system {@link android.app.NotificationManager}. By default, a notification is
491 * shown.
Steve Howarda2709362010-07-02 17:12:48 -0700492 *
Steve Howard8e15afe2010-07-28 17:12:40 -0700493 * If set to false, this requires the permission
494 * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
495 *
496 * @param show whether the download manager should show a notification for this download.
Steve Howarda2709362010-07-02 17:12:48 -0700497 * @return this object
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700498 * @deprecated use {@link #setNotificationVisibility(int)}
Steve Howarda2709362010-07-02 17:12:48 -0700499 */
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700500 @Deprecated
Steve Howard8e15afe2010-07-28 17:12:40 -0700501 public Request setShowRunningNotification(boolean show) {
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700502 return (show) ? setNotificationVisibility(VISIBILITY_VISIBLE) :
503 setNotificationVisibility(VISIBILITY_HIDDEN);
504 }
505
506 /**
507 * Control whether a system notification is posted by the download manager while this
508 * download is running or when it is completed.
509 * If enabled, the download manager posts notifications about downloads
510 * through the system {@link android.app.NotificationManager}.
511 * By default, a notification is shown only when the download is in progress.
512 *<p>
513 * It can take the following values: {@link #VISIBILITY_HIDDEN},
514 * {@link #VISIBILITY_VISIBLE},
515 * {@link #VISIBILITY_VISIBLE_NOTIFY_COMPLETED}.
516 *<p>
517 * If set to {@link #VISIBILITY_HIDDEN}, this requires the permission
518 * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
519 *
520 * @param visibility the visibility setting value
521 * @return this object
522 */
523 public Request setNotificationVisibility(int visibility) {
524 mNotificationVisibility = visibility;
Steve Howarda2709362010-07-02 17:12:48 -0700525 return this;
526 }
527
Steve Howardb8e07a52010-07-21 14:53:21 -0700528 /**
529 * Restrict the types of networks over which this download may proceed. By default, all
530 * network types are allowed.
531 * @param flags any combination of the NETWORK_* bit flags.
532 * @return this object
533 */
Steve Howarda2709362010-07-02 17:12:48 -0700534 public Request setAllowedNetworkTypes(int flags) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700535 mAllowedNetworkTypes = flags;
536 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700537 }
538
Steve Howardb8e07a52010-07-21 14:53:21 -0700539 /**
540 * Set whether this download may proceed over a roaming connection. By default, roaming is
541 * allowed.
542 * @param allowed whether to allow a roaming connection to be used
543 * @return this object
544 */
Steve Howarda2709362010-07-02 17:12:48 -0700545 public Request setAllowedOverRoaming(boolean allowed) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700546 mRoamingAllowed = allowed;
547 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700548 }
549
550 /**
Steve Howard90fb15a2010-09-09 16:13:41 -0700551 * Set whether this download should be displayed in the system's Downloads UI. True by
552 * default.
553 * @param isVisible whether to display this download in the Downloads UI
554 * @return this object
555 */
556 public Request setVisibleInDownloadsUi(boolean isVisible) {
557 mIsVisibleInDownloadsUi = isVisible;
558 return this;
559 }
560
561 /**
Steve Howarda2709362010-07-02 17:12:48 -0700562 * @return ContentValues to be passed to DownloadProvider.insert()
563 */
Steve Howardb8e07a52010-07-21 14:53:21 -0700564 ContentValues toContentValues(String packageName) {
Steve Howarda2709362010-07-02 17:12:48 -0700565 ContentValues values = new ContentValues();
566 assert mUri != null;
Vasu Norief7e33b2010-10-20 13:26:02 -0700567 values.put(Downloads.Impl.COLUMN_URI, mUri.toString());
Steve Howardb8e07a52010-07-21 14:53:21 -0700568 values.put(Downloads.Impl.COLUMN_IS_PUBLIC_API, true);
Vasu Norief7e33b2010-10-20 13:26:02 -0700569 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE, packageName);
Steve Howarda2709362010-07-02 17:12:48 -0700570
571 if (mDestinationUri != null) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700572 values.put(Downloads.Impl.COLUMN_DESTINATION, Downloads.Impl.DESTINATION_FILE_URI);
573 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, mDestinationUri.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700574 } else {
Vasu Norief7e33b2010-10-20 13:26:02 -0700575 values.put(Downloads.Impl.COLUMN_DESTINATION,
576 Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE);
Steve Howarda2709362010-07-02 17:12:48 -0700577 }
578
579 if (!mRequestHeaders.isEmpty()) {
Steve Howardea9147d2010-07-13 19:02:45 -0700580 encodeHttpHeaders(values);
Steve Howarda2709362010-07-02 17:12:48 -0700581 }
582
Vasu Norief7e33b2010-10-20 13:26:02 -0700583 putIfNonNull(values, Downloads.Impl.COLUMN_TITLE, mTitle);
584 putIfNonNull(values, Downloads.Impl.COLUMN_DESCRIPTION, mDescription);
585 putIfNonNull(values, Downloads.Impl.COLUMN_MIME_TYPE, mMimeType);
Steve Howarda2709362010-07-02 17:12:48 -0700586
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700587 values.put(Downloads.Impl.COLUMN_VISIBILITY, mNotificationVisibility);
Steve Howardb8e07a52010-07-21 14:53:21 -0700588 values.put(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES, mAllowedNetworkTypes);
589 values.put(Downloads.Impl.COLUMN_ALLOW_ROAMING, mRoamingAllowed);
Steve Howard90fb15a2010-09-09 16:13:41 -0700590 values.put(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, mIsVisibleInDownloadsUi);
Steve Howardb8e07a52010-07-21 14:53:21 -0700591
Steve Howarda2709362010-07-02 17:12:48 -0700592 return values;
593 }
594
Steve Howardea9147d2010-07-13 19:02:45 -0700595 private void encodeHttpHeaders(ContentValues values) {
596 int index = 0;
Steve Howard4f564cd2010-09-22 15:57:25 -0700597 for (Pair<String, String> header : mRequestHeaders) {
598 String headerString = header.first + ": " + header.second;
Steve Howardea9147d2010-07-13 19:02:45 -0700599 values.put(Downloads.Impl.RequestHeaders.INSERT_KEY_PREFIX + index, headerString);
600 index++;
601 }
602 }
603
Steve Howard4f564cd2010-09-22 15:57:25 -0700604 private void putIfNonNull(ContentValues contentValues, String key, Object value) {
Steve Howarda2709362010-07-02 17:12:48 -0700605 if (value != null) {
Steve Howard4f564cd2010-09-22 15:57:25 -0700606 contentValues.put(key, value.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700607 }
608 }
609 }
610
611 /**
612 * This class may be used to filter download manager queries.
613 */
614 public static class Query {
Steve Howardf054e192010-09-01 18:26:26 -0700615 /**
616 * Constant for use with {@link #orderBy}
617 * @hide
618 */
619 public static final int ORDER_ASCENDING = 1;
620
621 /**
622 * Constant for use with {@link #orderBy}
623 * @hide
624 */
625 public static final int ORDER_DESCENDING = 2;
626
Steve Howard64c48b82010-10-07 17:53:52 -0700627 private long[] mIds = null;
Steve Howarda2709362010-07-02 17:12:48 -0700628 private Integer mStatusFlags = null;
Vasu Norief7e33b2010-10-20 13:26:02 -0700629 private String mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
Steve Howardf054e192010-09-01 18:26:26 -0700630 private int mOrderDirection = ORDER_DESCENDING;
Steve Howard90fb15a2010-09-09 16:13:41 -0700631 private boolean mOnlyIncludeVisibleInDownloadsUi = false;
Steve Howarda2709362010-07-02 17:12:48 -0700632
633 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700634 * Include only the downloads with the given IDs.
Steve Howarda2709362010-07-02 17:12:48 -0700635 * @return this object
636 */
Steve Howard64c48b82010-10-07 17:53:52 -0700637 public Query setFilterById(long... ids) {
638 mIds = ids;
Steve Howarda2709362010-07-02 17:12:48 -0700639 return this;
640 }
641
642 /**
643 * Include only downloads with status matching any the given status flags.
644 * @param flags any combination of the STATUS_* bit flags
645 * @return this object
646 */
647 public Query setFilterByStatus(int flags) {
648 mStatusFlags = flags;
649 return this;
650 }
651
652 /**
Steve Howard90fb15a2010-09-09 16:13:41 -0700653 * Controls whether this query includes downloads not visible in the system's Downloads UI.
654 * @param value if true, this query will only include downloads that should be displayed in
655 * the system's Downloads UI; if false (the default), this query will include
656 * both visible and invisible downloads.
657 * @return this object
658 * @hide
659 */
660 public Query setOnlyIncludeVisibleInDownloadsUi(boolean value) {
661 mOnlyIncludeVisibleInDownloadsUi = value;
662 return this;
663 }
664
665 /**
Steve Howardf054e192010-09-01 18:26:26 -0700666 * Change the sort order of the returned Cursor.
667 *
668 * @param column one of the COLUMN_* constants; currently, only
669 * {@link #COLUMN_LAST_MODIFIED_TIMESTAMP} and {@link #COLUMN_TOTAL_SIZE_BYTES} are
670 * supported.
671 * @param direction either {@link #ORDER_ASCENDING} or {@link #ORDER_DESCENDING}
672 * @return this object
673 * @hide
674 */
675 public Query orderBy(String column, int direction) {
676 if (direction != ORDER_ASCENDING && direction != ORDER_DESCENDING) {
677 throw new IllegalArgumentException("Invalid direction: " + direction);
678 }
679
680 if (column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP)) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700681 mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
Steve Howardf054e192010-09-01 18:26:26 -0700682 } else if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700683 mOrderByColumn = Downloads.Impl.COLUMN_TOTAL_BYTES;
Steve Howardf054e192010-09-01 18:26:26 -0700684 } else {
685 throw new IllegalArgumentException("Cannot order by " + column);
686 }
687 mOrderDirection = direction;
688 return this;
689 }
690
691 /**
Steve Howarda2709362010-07-02 17:12:48 -0700692 * Run this query using the given ContentResolver.
693 * @param projection the projection to pass to ContentResolver.query()
694 * @return the Cursor returned by ContentResolver.query()
695 */
Steve Howardeca77fc2010-09-12 18:49:08 -0700696 Cursor runQuery(ContentResolver resolver, String[] projection, Uri baseUri) {
697 Uri uri = baseUri;
Steve Howard90fb15a2010-09-09 16:13:41 -0700698 List<String> selectionParts = new ArrayList<String>();
Steve Howard64c48b82010-10-07 17:53:52 -0700699 String[] selectionArgs = null;
Steve Howarda2709362010-07-02 17:12:48 -0700700
Steve Howard64c48b82010-10-07 17:53:52 -0700701 if (mIds != null) {
702 selectionParts.add(getWhereClauseForIds(mIds));
703 selectionArgs = getWhereArgsForIds(mIds);
Steve Howarda2709362010-07-02 17:12:48 -0700704 }
705
706 if (mStatusFlags != null) {
707 List<String> parts = new ArrayList<String>();
708 if ((mStatusFlags & STATUS_PENDING) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700709 parts.add(statusClause("=", Downloads.Impl.STATUS_PENDING));
Steve Howarda2709362010-07-02 17:12:48 -0700710 }
711 if ((mStatusFlags & STATUS_RUNNING) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700712 parts.add(statusClause("=", Downloads.Impl.STATUS_RUNNING));
Steve Howarda2709362010-07-02 17:12:48 -0700713 }
714 if ((mStatusFlags & STATUS_PAUSED) != 0) {
Steve Howard3e8c1d32010-09-29 17:03:32 -0700715 parts.add(statusClause("=", Downloads.Impl.STATUS_PAUSED_BY_APP));
716 parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_TO_RETRY));
717 parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_FOR_NETWORK));
718 parts.add(statusClause("=", Downloads.Impl.STATUS_QUEUED_FOR_WIFI));
Steve Howarda2709362010-07-02 17:12:48 -0700719 }
720 if ((mStatusFlags & STATUS_SUCCESSFUL) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700721 parts.add(statusClause("=", Downloads.Impl.STATUS_SUCCESS));
Steve Howarda2709362010-07-02 17:12:48 -0700722 }
723 if ((mStatusFlags & STATUS_FAILED) != 0) {
724 parts.add("(" + statusClause(">=", 400)
725 + " AND " + statusClause("<", 600) + ")");
726 }
Steve Howard90fb15a2010-09-09 16:13:41 -0700727 selectionParts.add(joinStrings(" OR ", parts));
Steve Howarda2709362010-07-02 17:12:48 -0700728 }
Steve Howardf054e192010-09-01 18:26:26 -0700729
Steve Howard90fb15a2010-09-09 16:13:41 -0700730 if (mOnlyIncludeVisibleInDownloadsUi) {
731 selectionParts.add(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI + " != '0'");
732 }
733
Vasu Nori216fa222010-10-12 23:08:13 -0700734 // only return rows which are not marked 'deleted = 1'
735 selectionParts.add(Downloads.Impl.COLUMN_DELETED + " != '1'");
736
Steve Howard90fb15a2010-09-09 16:13:41 -0700737 String selection = joinStrings(" AND ", selectionParts);
Steve Howardf054e192010-09-01 18:26:26 -0700738 String orderDirection = (mOrderDirection == ORDER_ASCENDING ? "ASC" : "DESC");
739 String orderBy = mOrderByColumn + " " + orderDirection;
740
Steve Howard64c48b82010-10-07 17:53:52 -0700741 return resolver.query(uri, projection, selection, selectionArgs, orderBy);
Steve Howarda2709362010-07-02 17:12:48 -0700742 }
743
744 private String joinStrings(String joiner, Iterable<String> parts) {
745 StringBuilder builder = new StringBuilder();
746 boolean first = true;
747 for (String part : parts) {
748 if (!first) {
749 builder.append(joiner);
750 }
751 builder.append(part);
752 first = false;
753 }
754 return builder.toString();
755 }
756
757 private String statusClause(String operator, int value) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700758 return Downloads.Impl.COLUMN_STATUS + operator + "'" + value + "'";
Steve Howarda2709362010-07-02 17:12:48 -0700759 }
760 }
761
762 private ContentResolver mResolver;
Steve Howardb8e07a52010-07-21 14:53:21 -0700763 private String mPackageName;
Steve Howardeca77fc2010-09-12 18:49:08 -0700764 private Uri mBaseUri = Downloads.Impl.CONTENT_URI;
Steve Howarda2709362010-07-02 17:12:48 -0700765
766 /**
767 * @hide
768 */
Steve Howardb8e07a52010-07-21 14:53:21 -0700769 public DownloadManager(ContentResolver resolver, String packageName) {
Steve Howarda2709362010-07-02 17:12:48 -0700770 mResolver = resolver;
Steve Howardb8e07a52010-07-21 14:53:21 -0700771 mPackageName = packageName;
Steve Howarda2709362010-07-02 17:12:48 -0700772 }
773
774 /**
Steve Howardeca77fc2010-09-12 18:49:08 -0700775 * Makes this object access the download provider through /all_downloads URIs rather than
776 * /my_downloads URIs, for clients that have permission to do so.
777 * @hide
778 */
779 public void setAccessAllDownloads(boolean accessAllDownloads) {
780 if (accessAllDownloads) {
781 mBaseUri = Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI;
782 } else {
783 mBaseUri = Downloads.Impl.CONTENT_URI;
784 }
785 }
786
787 /**
Steve Howarda2709362010-07-02 17:12:48 -0700788 * Enqueue a new download. The download will start automatically once the download manager is
789 * ready to execute it and connectivity is available.
790 *
791 * @param request the parameters specifying this download
792 * @return an ID for the download, unique across the system. This ID is used to make future
793 * calls related to this download.
794 */
795 public long enqueue(Request request) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700796 ContentValues values = request.toContentValues(mPackageName);
Vasu Norief7e33b2010-10-20 13:26:02 -0700797 Uri downloadUri = mResolver.insert(Downloads.Impl.CONTENT_URI, values);
Steve Howarda2709362010-07-02 17:12:48 -0700798 long id = Long.parseLong(downloadUri.getLastPathSegment());
799 return id;
800 }
801
802 /**
Vasu Nori216fa222010-10-12 23:08:13 -0700803 * Marks the specified download as 'to be deleted'. This is done when a completed download
804 * is to be removed but the row was stored without enough info to delete the corresponding
805 * metadata from Mediaprovider database. Actual cleanup of this row is done in DownloadService.
806 *
807 * @param ids the IDs of the downloads to be marked 'deleted'
808 * @return the number of downloads actually updated
809 * @hide
810 */
811 public int markRowDeleted(long... ids) {
812 if (ids == null || ids.length == 0) {
813 // called with nothing to remove!
814 throw new IllegalArgumentException("input param 'ids' can't be null");
815 }
816 ContentValues values = new ContentValues();
817 values.put(Downloads.Impl.COLUMN_DELETED, 1);
818 return mResolver.update(mBaseUri, values, getWhereClauseForIds(ids),
819 getWhereArgsForIds(ids));
820 }
821
822 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700823 * Cancel downloads and remove them from the download manager. Each download will be stopped if
Steve Howarda2709362010-07-02 17:12:48 -0700824 * it was running, and it will no longer be accessible through the download manager. If a file
Steve Howard64c48b82010-10-07 17:53:52 -0700825 * was already downloaded to external storage, it will not be deleted.
Steve Howarda2709362010-07-02 17:12:48 -0700826 *
Steve Howard64c48b82010-10-07 17:53:52 -0700827 * @param ids the IDs of the downloads to remove
828 * @return the number of downloads actually removed
Steve Howarda2709362010-07-02 17:12:48 -0700829 */
Steve Howard64c48b82010-10-07 17:53:52 -0700830 public int remove(long... ids) {
Vasu Norie7be6bd2010-10-10 14:58:08 -0700831 if (ids == null || ids.length == 0) {
832 // called with nothing to remove!
833 throw new IllegalArgumentException("input param 'ids' can't be null");
Steve Howarda2709362010-07-02 17:12:48 -0700834 }
Vasu Norie7be6bd2010-10-10 14:58:08 -0700835 return mResolver.delete(mBaseUri, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
Steve Howarda2709362010-07-02 17:12:48 -0700836 }
837
838 /**
839 * Query the download manager about downloads that have been requested.
840 * @param query parameters specifying filters for this query
841 * @return a Cursor over the result set of downloads, with columns consisting of all the
842 * COLUMN_* constants.
843 */
844 public Cursor query(Query query) {
Steve Howardeca77fc2010-09-12 18:49:08 -0700845 Cursor underlyingCursor = query.runQuery(mResolver, UNDERLYING_COLUMNS, mBaseUri);
Steve Howardf054e192010-09-01 18:26:26 -0700846 if (underlyingCursor == null) {
847 return null;
848 }
Steve Howardeca77fc2010-09-12 18:49:08 -0700849 return new CursorTranslator(underlyingCursor, mBaseUri);
Steve Howarda2709362010-07-02 17:12:48 -0700850 }
851
852 /**
853 * Open a downloaded file for reading. The download must have completed.
854 * @param id the ID of the download
855 * @return a read-only {@link ParcelFileDescriptor}
856 * @throws FileNotFoundException if the destination file does not already exist
857 */
858 public ParcelFileDescriptor openDownloadedFile(long id) throws FileNotFoundException {
859 return mResolver.openFileDescriptor(getDownloadUri(id), "r");
860 }
861
862 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700863 * Restart the given downloads, which must have already completed (successfully or not). This
Steve Howard90fb15a2010-09-09 16:13:41 -0700864 * method will only work when called from within the download manager's process.
Steve Howard64c48b82010-10-07 17:53:52 -0700865 * @param ids the IDs of the downloads
Steve Howard90fb15a2010-09-09 16:13:41 -0700866 * @hide
867 */
Steve Howard64c48b82010-10-07 17:53:52 -0700868 public void restartDownload(long... ids) {
869 Cursor cursor = query(new Query().setFilterById(ids));
Steve Howard90fb15a2010-09-09 16:13:41 -0700870 try {
Steve Howard64c48b82010-10-07 17:53:52 -0700871 for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
872 int status = cursor.getInt(cursor.getColumnIndex(COLUMN_STATUS));
873 if (status != STATUS_SUCCESSFUL && status != STATUS_FAILED) {
874 throw new IllegalArgumentException("Cannot restart incomplete download: "
875 + cursor.getLong(cursor.getColumnIndex(COLUMN_ID)));
876 }
Steve Howard90fb15a2010-09-09 16:13:41 -0700877 }
878 } finally {
879 cursor.close();
880 }
881
882 ContentValues values = new ContentValues();
883 values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, 0);
884 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, -1);
885 values.putNull(Downloads.Impl._DATA);
886 values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING);
Steve Howard64c48b82010-10-07 17:53:52 -0700887 mResolver.update(mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
Steve Howard90fb15a2010-09-09 16:13:41 -0700888 }
889
890 /**
Steve Howarda2709362010-07-02 17:12:48 -0700891 * Get the DownloadProvider URI for the download with the given ID.
892 */
Steve Howardeca77fc2010-09-12 18:49:08 -0700893 Uri getDownloadUri(long id) {
894 return ContentUris.withAppendedId(mBaseUri, id);
Steve Howarda2709362010-07-02 17:12:48 -0700895 }
896
897 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700898 * Get a parameterized SQL WHERE clause to select a bunch of IDs.
899 */
900 static String getWhereClauseForIds(long[] ids) {
901 StringBuilder whereClause = new StringBuilder();
Vasu Norie7be6bd2010-10-10 14:58:08 -0700902 whereClause.append("(");
Steve Howard64c48b82010-10-07 17:53:52 -0700903 for (int i = 0; i < ids.length; i++) {
904 if (i > 0) {
Vasu Norie7be6bd2010-10-10 14:58:08 -0700905 whereClause.append("OR ");
Steve Howard64c48b82010-10-07 17:53:52 -0700906 }
Vasu Norie7be6bd2010-10-10 14:58:08 -0700907 whereClause.append(Downloads.Impl._ID);
908 whereClause.append(" = ? ");
Steve Howard64c48b82010-10-07 17:53:52 -0700909 }
910 whereClause.append(")");
911 return whereClause.toString();
912 }
913
914 /**
915 * Get the selection args for a clause returned by {@link #getWhereClauseForIds(long[])}.
916 */
917 static String[] getWhereArgsForIds(long[] ids) {
918 String[] whereArgs = new String[ids.length];
919 for (int i = 0; i < ids.length; i++) {
920 whereArgs[i] = Long.toString(ids[i]);
921 }
922 return whereArgs;
923 }
924
925 /**
Steve Howarda2709362010-07-02 17:12:48 -0700926 * This class wraps a cursor returned by DownloadProvider -- the "underlying cursor" -- and
927 * presents a different set of columns, those defined in the DownloadManager.COLUMN_* constants.
928 * Some columns correspond directly to underlying values while others are computed from
929 * underlying data.
930 */
931 private static class CursorTranslator extends CursorWrapper {
Steve Howardeca77fc2010-09-12 18:49:08 -0700932 private Uri mBaseUri;
933
934 public CursorTranslator(Cursor cursor, Uri baseUri) {
Steve Howarda2709362010-07-02 17:12:48 -0700935 super(cursor);
Steve Howardeca77fc2010-09-12 18:49:08 -0700936 mBaseUri = baseUri;
Steve Howarda2709362010-07-02 17:12:48 -0700937 }
938
939 @Override
940 public int getColumnIndex(String columnName) {
941 return Arrays.asList(COLUMNS).indexOf(columnName);
942 }
943
944 @Override
945 public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException {
946 int index = getColumnIndex(columnName);
947 if (index == -1) {
Steve Howardf054e192010-09-01 18:26:26 -0700948 throw new IllegalArgumentException("No such column: " + columnName);
Steve Howarda2709362010-07-02 17:12:48 -0700949 }
950 return index;
951 }
952
953 @Override
954 public String getColumnName(int columnIndex) {
955 int numColumns = COLUMNS.length;
956 if (columnIndex < 0 || columnIndex >= numColumns) {
957 throw new IllegalArgumentException("Invalid column index " + columnIndex + ", "
958 + numColumns + " columns exist");
959 }
960 return COLUMNS[columnIndex];
961 }
962
963 @Override
964 public String[] getColumnNames() {
965 String[] returnColumns = new String[COLUMNS.length];
966 System.arraycopy(COLUMNS, 0, returnColumns, 0, COLUMNS.length);
967 return returnColumns;
968 }
969
970 @Override
971 public int getColumnCount() {
972 return COLUMNS.length;
973 }
974
975 @Override
976 public byte[] getBlob(int columnIndex) {
977 throw new UnsupportedOperationException();
978 }
979
980 @Override
981 public double getDouble(int columnIndex) {
982 return getLong(columnIndex);
983 }
984
985 private boolean isLongColumn(String column) {
986 return LONG_COLUMNS.contains(column);
987 }
988
989 @Override
990 public float getFloat(int columnIndex) {
991 return (float) getDouble(columnIndex);
992 }
993
994 @Override
995 public int getInt(int columnIndex) {
996 return (int) getLong(columnIndex);
997 }
998
999 @Override
1000 public long getLong(int columnIndex) {
1001 return translateLong(getColumnName(columnIndex));
1002 }
1003
1004 @Override
1005 public short getShort(int columnIndex) {
1006 return (short) getLong(columnIndex);
1007 }
1008
1009 @Override
1010 public String getString(int columnIndex) {
1011 return translateString(getColumnName(columnIndex));
1012 }
1013
1014 private String translateString(String column) {
1015 if (isLongColumn(column)) {
1016 return Long.toString(translateLong(column));
1017 }
1018 if (column.equals(COLUMN_TITLE)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001019 return getUnderlyingString(Downloads.Impl.COLUMN_TITLE);
Steve Howarda2709362010-07-02 17:12:48 -07001020 }
1021 if (column.equals(COLUMN_DESCRIPTION)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001022 return getUnderlyingString(Downloads.Impl.COLUMN_DESCRIPTION);
Steve Howarda2709362010-07-02 17:12:48 -07001023 }
1024 if (column.equals(COLUMN_URI)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001025 return getUnderlyingString(Downloads.Impl.COLUMN_URI);
Steve Howarda2709362010-07-02 17:12:48 -07001026 }
1027 if (column.equals(COLUMN_MEDIA_TYPE)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001028 return getUnderlyingString(Downloads.Impl.COLUMN_MIME_TYPE);
Steve Howarda2709362010-07-02 17:12:48 -07001029 }
Doug Zongkeree04af32010-10-08 13:42:16 -07001030 if (column.equals(COLUMN_LOCAL_FILENAME)) {
1031 return getUnderlyingString(Downloads.Impl._DATA);
1032 }
Vasu Nori216fa222010-10-12 23:08:13 -07001033 if (column.equals(COLUMN_MEDIAPROVIDER_URI)) {
1034 return getUnderlyingString(Downloads.Impl.COLUMN_MEDIAPROVIDER_URI);
1035 }
Steve Howard8651bd52010-08-03 12:35:32 -07001036
Steve Howarda2709362010-07-02 17:12:48 -07001037 assert column.equals(COLUMN_LOCAL_URI);
Steve Howardeca77fc2010-09-12 18:49:08 -07001038 return getLocalUri();
1039 }
1040
1041 private String getLocalUri() {
Steve Howardeca77fc2010-09-12 18:49:08 -07001042 long destinationType = getUnderlyingLong(Downloads.Impl.COLUMN_DESTINATION);
1043 if (destinationType == Downloads.Impl.DESTINATION_FILE_URI) {
Steve Howarda9e87c92010-09-16 12:02:03 -07001044 // return client-provided file URI for external download
1045 return getUnderlyingString(Downloads.Impl.COLUMN_FILE_NAME_HINT);
Steve Howardeca77fc2010-09-12 18:49:08 -07001046 }
1047
Steve Howardbb0d23b2010-09-22 18:56:29 -07001048 if (destinationType == Downloads.Impl.DESTINATION_EXTERNAL) {
1049 // return stored destination for legacy external download
Steve Howard99047d72010-09-29 17:41:37 -07001050 String localPath = getUnderlyingString(Downloads.Impl._DATA);
1051 if (localPath == null) {
1052 return null;
1053 }
1054 return Uri.fromFile(new File(localPath)).toString();
Steve Howardbb0d23b2010-09-22 18:56:29 -07001055 }
1056
Steve Howardeca77fc2010-09-12 18:49:08 -07001057 // return content URI for cache download
1058 long downloadId = getUnderlyingLong(Downloads.Impl._ID);
1059 return ContentUris.withAppendedId(mBaseUri, downloadId).toString();
Steve Howarda2709362010-07-02 17:12:48 -07001060 }
1061
1062 private long translateLong(String column) {
1063 if (!isLongColumn(column)) {
1064 // mimic behavior of underlying cursor -- most likely, throw NumberFormatException
1065 return Long.valueOf(translateString(column));
1066 }
1067
1068 if (column.equals(COLUMN_ID)) {
1069 return getUnderlyingLong(Downloads.Impl._ID);
1070 }
1071 if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001072 return getUnderlyingLong(Downloads.Impl.COLUMN_TOTAL_BYTES);
Steve Howarda2709362010-07-02 17:12:48 -07001073 }
1074 if (column.equals(COLUMN_STATUS)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001075 return translateStatus((int) getUnderlyingLong(Downloads.Impl.COLUMN_STATUS));
Steve Howarda2709362010-07-02 17:12:48 -07001076 }
Steve Howard3e8c1d32010-09-29 17:03:32 -07001077 if (column.equals(COLUMN_REASON)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001078 return getReason((int) getUnderlyingLong(Downloads.Impl.COLUMN_STATUS));
Steve Howarda2709362010-07-02 17:12:48 -07001079 }
1080 if (column.equals(COLUMN_BYTES_DOWNLOADED_SO_FAR)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001081 return getUnderlyingLong(Downloads.Impl.COLUMN_CURRENT_BYTES);
Steve Howarda2709362010-07-02 17:12:48 -07001082 }
Steve Howardadcb6972010-07-12 17:09:25 -07001083 assert column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP);
Vasu Norief7e33b2010-10-20 13:26:02 -07001084 return getUnderlyingLong(Downloads.Impl.COLUMN_LAST_MODIFICATION);
Steve Howarda2709362010-07-02 17:12:48 -07001085 }
1086
Steve Howard3e8c1d32010-09-29 17:03:32 -07001087 private long getReason(int status) {
1088 switch (translateStatus(status)) {
1089 case STATUS_FAILED:
1090 return getErrorCode(status);
1091
1092 case STATUS_PAUSED:
1093 return getPausedReason(status);
1094
1095 default:
1096 return 0; // arbitrary value when status is not an error
Steve Howarda2709362010-07-02 17:12:48 -07001097 }
Steve Howard3e8c1d32010-09-29 17:03:32 -07001098 }
1099
1100 private long getPausedReason(int status) {
1101 switch (status) {
1102 case Downloads.Impl.STATUS_WAITING_TO_RETRY:
1103 return PAUSED_WAITING_TO_RETRY;
1104
1105 case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
1106 return PAUSED_WAITING_FOR_NETWORK;
1107
1108 case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
1109 return PAUSED_QUEUED_FOR_WIFI;
1110
1111 default:
1112 return PAUSED_UNKNOWN;
1113 }
1114 }
1115
1116 private long getErrorCode(int status) {
Steve Howard33bbd122010-08-02 17:51:29 -07001117 if ((400 <= status && status < Downloads.Impl.MIN_ARTIFICIAL_ERROR_STATUS)
1118 || (500 <= status && status < 600)) {
Steve Howarda2709362010-07-02 17:12:48 -07001119 // HTTP status code
1120 return status;
1121 }
1122
1123 switch (status) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001124 case Downloads.Impl.STATUS_FILE_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001125 return ERROR_FILE_ERROR;
1126
Vasu Norief7e33b2010-10-20 13:26:02 -07001127 case Downloads.Impl.STATUS_UNHANDLED_HTTP_CODE:
1128 case Downloads.Impl.STATUS_UNHANDLED_REDIRECT:
Steve Howarda2709362010-07-02 17:12:48 -07001129 return ERROR_UNHANDLED_HTTP_CODE;
1130
Vasu Norief7e33b2010-10-20 13:26:02 -07001131 case Downloads.Impl.STATUS_HTTP_DATA_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001132 return ERROR_HTTP_DATA_ERROR;
1133
Vasu Norief7e33b2010-10-20 13:26:02 -07001134 case Downloads.Impl.STATUS_TOO_MANY_REDIRECTS:
Steve Howarda2709362010-07-02 17:12:48 -07001135 return ERROR_TOO_MANY_REDIRECTS;
1136
Vasu Norief7e33b2010-10-20 13:26:02 -07001137 case Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001138 return ERROR_INSUFFICIENT_SPACE;
1139
Vasu Norief7e33b2010-10-20 13:26:02 -07001140 case Downloads.Impl.STATUS_DEVICE_NOT_FOUND_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001141 return ERROR_DEVICE_NOT_FOUND;
1142
Steve Howard33bbd122010-08-02 17:51:29 -07001143 case Downloads.Impl.STATUS_CANNOT_RESUME:
1144 return ERROR_CANNOT_RESUME;
1145
Steve Howarda9e87c92010-09-16 12:02:03 -07001146 case Downloads.Impl.STATUS_FILE_ALREADY_EXISTS_ERROR:
1147 return ERROR_FILE_ALREADY_EXISTS;
1148
Steve Howarda2709362010-07-02 17:12:48 -07001149 default:
1150 return ERROR_UNKNOWN;
1151 }
1152 }
1153
1154 private long getUnderlyingLong(String column) {
1155 return super.getLong(super.getColumnIndex(column));
1156 }
1157
1158 private String getUnderlyingString(String column) {
1159 return super.getString(super.getColumnIndex(column));
1160 }
1161
Steve Howard3e8c1d32010-09-29 17:03:32 -07001162 private int translateStatus(int status) {
Steve Howarda2709362010-07-02 17:12:48 -07001163 switch (status) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001164 case Downloads.Impl.STATUS_PENDING:
Steve Howarda2709362010-07-02 17:12:48 -07001165 return STATUS_PENDING;
1166
Vasu Norief7e33b2010-10-20 13:26:02 -07001167 case Downloads.Impl.STATUS_RUNNING:
Steve Howarda2709362010-07-02 17:12:48 -07001168 return STATUS_RUNNING;
1169
Steve Howard3e8c1d32010-09-29 17:03:32 -07001170 case Downloads.Impl.STATUS_PAUSED_BY_APP:
1171 case Downloads.Impl.STATUS_WAITING_TO_RETRY:
1172 case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
1173 case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
Steve Howarda2709362010-07-02 17:12:48 -07001174 return STATUS_PAUSED;
1175
Vasu Norief7e33b2010-10-20 13:26:02 -07001176 case Downloads.Impl.STATUS_SUCCESS:
Steve Howarda2709362010-07-02 17:12:48 -07001177 return STATUS_SUCCESSFUL;
1178
1179 default:
Vasu Norief7e33b2010-10-20 13:26:02 -07001180 assert Downloads.Impl.isStatusError(status);
Steve Howarda2709362010-07-02 17:12:48 -07001181 return STATUS_FAILED;
1182 }
1183 }
1184 }
1185}