blob: 08ccab6c6e03f202f18e2992b7d2d43ef7c4967e [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;
Vasu Nori5be894e2010-11-02 21:55:30 -070030import android.util.Log;
Steve Howard4f564cd2010-09-22 15:57:25 -070031import android.util.Pair;
Steve Howarda2709362010-07-02 17:12:48 -070032
Steve Howard4f564cd2010-09-22 15:57:25 -070033import java.io.File;
Steve Howarda2709362010-07-02 17:12:48 -070034import java.io.FileNotFoundException;
35import java.util.ArrayList;
36import java.util.Arrays;
Steve Howarda2709362010-07-02 17:12:48 -070037import java.util.HashSet;
38import java.util.List;
Steve Howarda2709362010-07-02 17:12:48 -070039import java.util.Set;
40
41/**
42 * The download manager is a system service that handles long-running HTTP downloads. Clients may
43 * request that a URI be downloaded to a particular destination file. The download manager will
44 * conduct the download in the background, taking care of HTTP interactions and retrying downloads
45 * after failures or across connectivity changes and system reboots.
46 *
47 * Instances of this class should be obtained through
48 * {@link android.content.Context#getSystemService(String)} by passing
49 * {@link android.content.Context#DOWNLOAD_SERVICE}.
Steve Howard610c4352010-09-30 18:30:04 -070050 *
51 * Apps that request downloads through this API should register a broadcast receiver for
52 * {@link #ACTION_NOTIFICATION_CLICKED} to appropriately handle when the user clicks on a running
53 * download in a notification or from the downloads UI.
Steve Howarda2709362010-07-02 17:12:48 -070054 */
55public class DownloadManager {
Vasu Norie7be6bd2010-10-10 14:58:08 -070056 private static final String TAG = "DownloadManager";
57
Steve Howarda2709362010-07-02 17:12:48 -070058 /**
59 * An identifier for a particular download, unique across the system. Clients use this ID to
60 * make subsequent calls related to the download.
61 */
Vasu Norief7e33b2010-10-20 13:26:02 -070062 public final static String COLUMN_ID = Downloads.Impl._ID;
Steve Howarda2709362010-07-02 17:12:48 -070063
64 /**
Steve Howard8651bd52010-08-03 12:35:32 -070065 * The client-supplied title for this download. This will be displayed in system notifications.
66 * Defaults to the empty string.
Steve Howarda2709362010-07-02 17:12:48 -070067 */
Vasu Norief7e33b2010-10-20 13:26:02 -070068 public final static String COLUMN_TITLE = Downloads.Impl.COLUMN_TITLE;
Steve Howarda2709362010-07-02 17:12:48 -070069
70 /**
71 * The client-supplied description of this download. This will be displayed in system
Steve Howard8651bd52010-08-03 12:35:32 -070072 * notifications. Defaults to the empty string.
Steve Howarda2709362010-07-02 17:12:48 -070073 */
Vasu Norief7e33b2010-10-20 13:26:02 -070074 public final static String COLUMN_DESCRIPTION = Downloads.Impl.COLUMN_DESCRIPTION;
Steve Howarda2709362010-07-02 17:12:48 -070075
76 /**
77 * URI to be downloaded.
78 */
Vasu Norief7e33b2010-10-20 13:26:02 -070079 public final static String COLUMN_URI = Downloads.Impl.COLUMN_URI;
Steve Howarda2709362010-07-02 17:12:48 -070080
81 /**
Steve Howard8651bd52010-08-03 12:35:32 -070082 * Internet Media Type of the downloaded file. If no value is provided upon creation, this will
83 * initially be null and will be filled in based on the server's response once the download has
84 * started.
Steve Howarda2709362010-07-02 17:12:48 -070085 *
86 * @see <a href="http://www.ietf.org/rfc/rfc1590.txt">RFC 1590, defining Media Types</a>
87 */
88 public final static String COLUMN_MEDIA_TYPE = "media_type";
89
90 /**
Steve Howard8651bd52010-08-03 12:35:32 -070091 * Total size of the download in bytes. This will initially be -1 and will be filled in once
92 * the download starts.
Steve Howarda2709362010-07-02 17:12:48 -070093 */
94 public final static String COLUMN_TOTAL_SIZE_BYTES = "total_size";
95
96 /**
97 * Uri where downloaded file will be stored. If a destination is supplied by client, that URI
Steve Howard8651bd52010-08-03 12:35:32 -070098 * will be used here. Otherwise, the value will initially be null and will be filled in with a
99 * generated URI once the download has started.
Steve Howarda2709362010-07-02 17:12:48 -0700100 */
101 public final static String COLUMN_LOCAL_URI = "local_uri";
102
103 /**
Doug Zongkeree04af32010-10-08 13:42:16 -0700104 * The pathname of the file where the download is stored.
105 */
106 public final static String COLUMN_LOCAL_FILENAME = "local_filename";
107
108 /**
Steve Howarda2709362010-07-02 17:12:48 -0700109 * Current status of the download, as one of the STATUS_* constants.
110 */
Vasu Norief7e33b2010-10-20 13:26:02 -0700111 public final static String COLUMN_STATUS = Downloads.Impl.COLUMN_STATUS;
Steve Howarda2709362010-07-02 17:12:48 -0700112
113 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700114 * Provides more detail on the status of the download. Its meaning depends on the value of
115 * {@link #COLUMN_STATUS}.
Steve Howarda2709362010-07-02 17:12:48 -0700116 *
Steve Howard3e8c1d32010-09-29 17:03:32 -0700117 * When {@link #COLUMN_STATUS} is {@link #STATUS_FAILED}, this indicates the type of error that
118 * occurred. If an HTTP error occurred, this will hold the HTTP status code as defined in RFC
119 * 2616. Otherwise, it will hold one of the ERROR_* constants.
120 *
121 * When {@link #COLUMN_STATUS} is {@link #STATUS_PAUSED}, this indicates why the download is
122 * paused. It will hold one of the PAUSED_* constants.
123 *
124 * If {@link #COLUMN_STATUS} is neither {@link #STATUS_FAILED} nor {@link #STATUS_PAUSED}, this
125 * column's value is undefined.
Steve Howarda2709362010-07-02 17:12:48 -0700126 *
127 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1.1">RFC 2616
128 * status codes</a>
129 */
Steve Howard3e8c1d32010-09-29 17:03:32 -0700130 public final static String COLUMN_REASON = "reason";
Steve Howarda2709362010-07-02 17:12:48 -0700131
132 /**
133 * Number of bytes download so far.
134 */
135 public final static String COLUMN_BYTES_DOWNLOADED_SO_FAR = "bytes_so_far";
136
137 /**
Steve Howardadcb6972010-07-12 17:09:25 -0700138 * Timestamp when the download was last modified, in {@link System#currentTimeMillis
Steve Howarda2709362010-07-02 17:12:48 -0700139 * System.currentTimeMillis()} (wall clock time in UTC).
140 */
Steve Howardadcb6972010-07-12 17:09:25 -0700141 public final static String COLUMN_LAST_MODIFIED_TIMESTAMP = "last_modified_timestamp";
Steve Howarda2709362010-07-02 17:12:48 -0700142
Vasu Nori216fa222010-10-12 23:08:13 -0700143 /**
144 * The URI to the corresponding entry in MediaProvider for this downloaded entry. It is
145 * used to delete the entries from MediaProvider database when it is deleted from the
146 * downloaded list.
147 */
Vasu Norief7e33b2010-10-20 13:26:02 -0700148 public static final String COLUMN_MEDIAPROVIDER_URI = Downloads.Impl.COLUMN_MEDIAPROVIDER_URI;
Steve Howarda2709362010-07-02 17:12:48 -0700149
150 /**
151 * Value of {@link #COLUMN_STATUS} when the download is waiting to start.
152 */
153 public final static int STATUS_PENDING = 1 << 0;
154
155 /**
156 * Value of {@link #COLUMN_STATUS} when the download is currently running.
157 */
158 public final static int STATUS_RUNNING = 1 << 1;
159
160 /**
161 * Value of {@link #COLUMN_STATUS} when the download is waiting to retry or resume.
162 */
163 public final static int STATUS_PAUSED = 1 << 2;
164
165 /**
166 * Value of {@link #COLUMN_STATUS} when the download has successfully completed.
167 */
168 public final static int STATUS_SUCCESSFUL = 1 << 3;
169
170 /**
171 * Value of {@link #COLUMN_STATUS} when the download has failed (and will not be retried).
172 */
173 public final static int STATUS_FAILED = 1 << 4;
174
175
176 /**
177 * Value of COLUMN_ERROR_CODE when the download has completed with an error that doesn't fit
178 * under any other error code.
179 */
180 public final static int ERROR_UNKNOWN = 1000;
181
182 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700183 * Value of {@link #COLUMN_REASON} when a storage issue arises which doesn't fit under any
Steve Howarda2709362010-07-02 17:12:48 -0700184 * other error code. Use the more specific {@link #ERROR_INSUFFICIENT_SPACE} and
185 * {@link #ERROR_DEVICE_NOT_FOUND} when appropriate.
186 */
187 public final static int ERROR_FILE_ERROR = 1001;
188
189 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700190 * Value of {@link #COLUMN_REASON} when an HTTP code was received that download manager
Steve Howarda2709362010-07-02 17:12:48 -0700191 * can't handle.
192 */
193 public final static int ERROR_UNHANDLED_HTTP_CODE = 1002;
194
195 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700196 * Value of {@link #COLUMN_REASON} when an error receiving or processing data occurred at
Steve Howarda2709362010-07-02 17:12:48 -0700197 * the HTTP level.
198 */
199 public final static int ERROR_HTTP_DATA_ERROR = 1004;
200
201 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700202 * Value of {@link #COLUMN_REASON} when there were too many redirects.
Steve Howarda2709362010-07-02 17:12:48 -0700203 */
204 public final static int ERROR_TOO_MANY_REDIRECTS = 1005;
205
206 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700207 * Value of {@link #COLUMN_REASON} when there was insufficient storage space. Typically,
Steve Howarda2709362010-07-02 17:12:48 -0700208 * this is because the SD card is full.
209 */
210 public final static int ERROR_INSUFFICIENT_SPACE = 1006;
211
212 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700213 * Value of {@link #COLUMN_REASON} when no external storage device was found. Typically,
Steve Howarda2709362010-07-02 17:12:48 -0700214 * this is because the SD card is not mounted.
215 */
216 public final static int ERROR_DEVICE_NOT_FOUND = 1007;
217
Steve Howardb8e07a52010-07-21 14:53:21 -0700218 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700219 * Value of {@link #COLUMN_REASON} when some possibly transient error occurred but we can't
Steve Howard33bbd122010-08-02 17:51:29 -0700220 * resume the download.
221 */
222 public final static int ERROR_CANNOT_RESUME = 1008;
223
224 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700225 * Value of {@link #COLUMN_REASON} when the requested destination file already exists (the
Steve Howarda9e87c92010-09-16 12:02:03 -0700226 * download manager will not overwrite an existing file).
227 */
228 public final static int ERROR_FILE_ALREADY_EXISTS = 1009;
229
230 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700231 * Value of {@link #COLUMN_REASON} when the download is paused because some network error
232 * occurred and the download manager is waiting before retrying the request.
233 */
234 public final static int PAUSED_WAITING_TO_RETRY = 1;
235
236 /**
237 * Value of {@link #COLUMN_REASON} when the download is waiting for network connectivity to
238 * proceed.
239 */
240 public final static int PAUSED_WAITING_FOR_NETWORK = 2;
241
242 /**
243 * Value of {@link #COLUMN_REASON} when the download exceeds a size limit for downloads over
244 * the mobile network and the download manager is waiting for a Wi-Fi connection to proceed.
245 */
246 public final static int PAUSED_QUEUED_FOR_WIFI = 3;
247
248 /**
249 * Value of {@link #COLUMN_REASON} when the download is paused for some other reason.
250 */
251 public final static int PAUSED_UNKNOWN = 4;
252
253 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700254 * Broadcast intent action sent by the download manager when a download completes.
255 */
256 public final static String ACTION_DOWNLOAD_COMPLETE = "android.intent.action.DOWNLOAD_COMPLETE";
257
258 /**
Steve Howard610c4352010-09-30 18:30:04 -0700259 * Broadcast intent action sent by the download manager when the user clicks on a running
260 * download, either from a system notification or from the downloads UI.
Steve Howardb8e07a52010-07-21 14:53:21 -0700261 */
262 public final static String ACTION_NOTIFICATION_CLICKED =
263 "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED";
264
265 /**
Steve Howarde78fc182010-09-24 14:59:36 -0700266 * Intent action to launch an activity to display all downloads.
267 */
268 public final static String ACTION_VIEW_DOWNLOADS = "android.intent.action.VIEW_DOWNLOADS";
269
270 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700271 * Intent extra included with {@link #ACTION_DOWNLOAD_COMPLETE} intents, indicating the ID (as a
272 * long) of the download that just completed.
273 */
274 public static final String EXTRA_DOWNLOAD_ID = "extra_download_id";
Steve Howarda2709362010-07-02 17:12:48 -0700275
Vasu Nori71b8c232010-10-27 15:22:19 -0700276 /**
277 * When clicks on multiple notifications are received, the following
278 * provides an array of download ids corresponding to the download notification that was
279 * clicked. It can be retrieved by the receiver of this
280 * Intent using {@link android.content.Intent#getLongArrayExtra(String)}.
281 */
282 public static final String EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS = "extra_click_download_ids";
283
Steve Howarda2709362010-07-02 17:12:48 -0700284 // this array must contain all public columns
285 private static final String[] COLUMNS = new String[] {
286 COLUMN_ID,
Vasu Nori216fa222010-10-12 23:08:13 -0700287 COLUMN_MEDIAPROVIDER_URI,
Vasu Nori5be894e2010-11-02 21:55:30 -0700288 Downloads.Impl.COLUMN_DESTINATION,
Steve Howarda2709362010-07-02 17:12:48 -0700289 COLUMN_TITLE,
290 COLUMN_DESCRIPTION,
291 COLUMN_URI,
292 COLUMN_MEDIA_TYPE,
293 COLUMN_TOTAL_SIZE_BYTES,
294 COLUMN_LOCAL_URI,
295 COLUMN_STATUS,
Steve Howard3e8c1d32010-09-29 17:03:32 -0700296 COLUMN_REASON,
Steve Howarda2709362010-07-02 17:12:48 -0700297 COLUMN_BYTES_DOWNLOADED_SO_FAR,
Doug Zongkeree04af32010-10-08 13:42:16 -0700298 COLUMN_LAST_MODIFIED_TIMESTAMP,
Vasu Nori5be894e2010-11-02 21:55:30 -0700299 COLUMN_LOCAL_FILENAME,
Steve Howarda2709362010-07-02 17:12:48 -0700300 };
301
302 // columns to request from DownloadProvider
303 private static final String[] UNDERLYING_COLUMNS = new String[] {
304 Downloads.Impl._ID,
Vasu Nori216fa222010-10-12 23:08:13 -0700305 Downloads.Impl.COLUMN_MEDIAPROVIDER_URI,
Vasu Nori5be894e2010-11-02 21:55:30 -0700306 Downloads.Impl.COLUMN_DESTINATION,
Vasu Norief7e33b2010-10-20 13:26:02 -0700307 Downloads.Impl.COLUMN_TITLE,
308 Downloads.Impl.COLUMN_DESCRIPTION,
309 Downloads.Impl.COLUMN_URI,
310 Downloads.Impl.COLUMN_MIME_TYPE,
311 Downloads.Impl.COLUMN_TOTAL_BYTES,
312 Downloads.Impl.COLUMN_STATUS,
313 Downloads.Impl.COLUMN_CURRENT_BYTES,
314 Downloads.Impl.COLUMN_LAST_MODIFICATION,
Steve Howarda9e87c92010-09-16 12:02:03 -0700315 Downloads.Impl.COLUMN_FILE_NAME_HINT,
Steve Howardbb0d23b2010-09-22 18:56:29 -0700316 Downloads.Impl._DATA,
Steve Howarda2709362010-07-02 17:12:48 -0700317 };
318
319 private static final Set<String> LONG_COLUMNS = new HashSet<String>(
Steve Howard3e8c1d32010-09-29 17:03:32 -0700320 Arrays.asList(COLUMN_ID, COLUMN_TOTAL_SIZE_BYTES, COLUMN_STATUS, COLUMN_REASON,
Vasu Nori5be894e2010-11-02 21:55:30 -0700321 COLUMN_BYTES_DOWNLOADED_SO_FAR, COLUMN_LAST_MODIFIED_TIMESTAMP,
322 Downloads.Impl.COLUMN_DESTINATION));
Steve Howarda2709362010-07-02 17:12:48 -0700323
324 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700325 * This class contains all the information necessary to request a new download. The URI is the
Steve Howarda2709362010-07-02 17:12:48 -0700326 * only required parameter.
Steve Howard4f564cd2010-09-22 15:57:25 -0700327 *
328 * Note that the default download destination is a shared volume where the system might delete
329 * your file if it needs to reclaim space for system use. If this is a problem, use a location
330 * on external storage (see {@link #setDestinationUri(Uri)}.
Steve Howarda2709362010-07-02 17:12:48 -0700331 */
332 public static class Request {
333 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700334 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
335 * {@link ConnectivityManager#TYPE_MOBILE}.
336 */
337 public static final int NETWORK_MOBILE = 1 << 0;
Steve Howarda2709362010-07-02 17:12:48 -0700338
Steve Howardb8e07a52010-07-21 14:53:21 -0700339 /**
340 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
341 * {@link ConnectivityManager#TYPE_WIFI}.
342 */
343 public static final int NETWORK_WIFI = 1 << 1;
344
Steve Howardb8e07a52010-07-21 14:53:21 -0700345 private Uri mUri;
346 private Uri mDestinationUri;
Steve Howard4f564cd2010-09-22 15:57:25 -0700347 private List<Pair<String, String>> mRequestHeaders = new ArrayList<Pair<String, String>>();
348 private CharSequence mTitle;
349 private CharSequence mDescription;
Steve Howard4f564cd2010-09-22 15:57:25 -0700350 private String mMimeType;
Steve Howardb8e07a52010-07-21 14:53:21 -0700351 private boolean mRoamingAllowed = true;
352 private int mAllowedNetworkTypes = ~0; // default to all network types allowed
Steve Howard90fb15a2010-09-09 16:13:41 -0700353 private boolean mIsVisibleInDownloadsUi = true;
Vasu Nori5be894e2010-11-02 21:55:30 -0700354 private boolean mScannable = false;
Steve Howarda2709362010-07-02 17:12:48 -0700355
356 /**
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700357 * This download is visible but only shows in the notifications
358 * while it's in progress.
359 */
360 public static final int VISIBILITY_VISIBLE = 0;
361
362 /**
363 * This download is visible and shows in the notifications while
364 * in progress and after completion.
365 */
366 public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED = 1;
367
368 /**
369 * This download doesn't show in the UI or in the notifications.
370 */
371 public static final int VISIBILITY_HIDDEN = 2;
372
373 /** can take any of the following values: {@link #VISIBILITY_HIDDEN}
374 * {@link #VISIBILITY_VISIBLE_NOTIFY_COMPLETED}, {@link #VISIBILITY_VISIBLE}
375 */
376 private int mNotificationVisibility = VISIBILITY_VISIBLE;
377
378 /**
Steve Howarda2709362010-07-02 17:12:48 -0700379 * @param uri the HTTP URI to download.
380 */
381 public Request(Uri uri) {
382 if (uri == null) {
383 throw new NullPointerException();
384 }
385 String scheme = uri.getScheme();
Paul Westbrook86a60192010-09-15 12:55:49 -0700386 if (scheme == null || (!scheme.equals("http") && !scheme.equals("https"))) {
387 throw new IllegalArgumentException("Can only download HTTP/HTTPS URIs: " + uri);
Steve Howarda2709362010-07-02 17:12:48 -0700388 }
389 mUri = uri;
390 }
391
392 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700393 * Set the local destination for the downloaded file. Must be a file URI to a path on
Steve Howarda2709362010-07-02 17:12:48 -0700394 * external storage, and the calling application must have the WRITE_EXTERNAL_STORAGE
395 * permission.
Vasu Nori5be894e2010-11-02 21:55:30 -0700396 * <p>
397 * The downloaded file is not scanned by MediaScanner.
398 * But it can be made scannable by calling {@link #allowScanningByMediaScanner()}.
399 * <p>
Steve Howard4f564cd2010-09-22 15:57:25 -0700400 * By default, downloads are saved to a generated filename in the shared download cache and
401 * may be deleted by the system at any time to reclaim space.
Steve Howarda2709362010-07-02 17:12:48 -0700402 *
403 * @return this object
404 */
405 public Request setDestinationUri(Uri uri) {
406 mDestinationUri = uri;
407 return this;
408 }
409
410 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700411 * Set the local destination for the downloaded file to a path within the application's
412 * external files directory (as returned by {@link Context#getExternalFilesDir(String)}.
Vasu Nori5be894e2010-11-02 21:55:30 -0700413 * <p>
414 * The downloaded file is not scanned by MediaScanner.
415 * But it can be made scannable by calling {@link #allowScanningByMediaScanner()}.
Steve Howard4f564cd2010-09-22 15:57:25 -0700416 *
417 * @param context the {@link Context} to use in determining the external files directory
418 * @param dirType the directory type to pass to {@link Context#getExternalFilesDir(String)}
419 * @param subPath the path within the external directory, including the destination filename
420 * @return this object
421 */
422 public Request setDestinationInExternalFilesDir(Context context, String dirType,
423 String subPath) {
424 setDestinationFromBase(context.getExternalFilesDir(dirType), subPath);
425 return this;
426 }
427
428 /**
429 * Set the local destination for the downloaded file to a path within the public external
430 * storage directory (as returned by
431 * {@link Environment#getExternalStoragePublicDirectory(String)}.
Vasu Nori5be894e2010-11-02 21:55:30 -0700432 *<p>
433 * The downloaded file is not scanned by MediaScanner.
434 * But it can be made scannable by calling {@link #allowScanningByMediaScanner()}.
Steve Howard4f564cd2010-09-22 15:57:25 -0700435 *
436 * @param dirType the directory type to pass to
437 * {@link Environment#getExternalStoragePublicDirectory(String)}
438 * @param subPath the path within the external directory, including the destination filename
439 * @return this object
440 */
441 public Request setDestinationInExternalPublicDir(String dirType, String subPath) {
442 setDestinationFromBase(Environment.getExternalStoragePublicDirectory(dirType), subPath);
443 return this;
444 }
445
446 private void setDestinationFromBase(File base, String subPath) {
447 if (subPath == null) {
448 throw new NullPointerException("subPath cannot be null");
449 }
450 mDestinationUri = Uri.withAppendedPath(Uri.fromFile(base), subPath);
451 }
452
453 /**
Vasu Nori5be894e2010-11-02 21:55:30 -0700454 * If the file to be downloaded is to be scanned by MediaScanner, this method
455 * should be called before {@link DownloadManager#enqueue(Request)} is called.
456 */
457 public void allowScanningByMediaScanner() {
458 mScannable = true;
459 }
460
461 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700462 * Add an HTTP header to be included with the download request. The header will be added to
463 * the end of the list.
Steve Howarda2709362010-07-02 17:12:48 -0700464 * @param header HTTP header name
465 * @param value header value
466 * @return this object
Steve Howard4f564cd2010-09-22 15:57:25 -0700467 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2">HTTP/1.1
468 * Message Headers</a>
Steve Howarda2709362010-07-02 17:12:48 -0700469 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700470 public Request addRequestHeader(String header, String value) {
471 if (header == null) {
472 throw new NullPointerException("header cannot be null");
473 }
474 if (header.contains(":")) {
475 throw new IllegalArgumentException("header may not contain ':'");
476 }
477 if (value == null) {
478 value = "";
479 }
480 mRequestHeaders.add(Pair.create(header, value));
Steve Howarda2709362010-07-02 17:12:48 -0700481 return this;
482 }
483
484 /**
Steve Howard610c4352010-09-30 18:30:04 -0700485 * Set the title of this download, to be displayed in notifications (if enabled). If no
486 * title is given, a default one will be assigned based on the download filename, once the
487 * download starts.
Steve Howarda2709362010-07-02 17:12:48 -0700488 * @return this object
489 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700490 public Request setTitle(CharSequence title) {
Steve Howarda2709362010-07-02 17:12:48 -0700491 mTitle = title;
492 return this;
493 }
494
495 /**
496 * Set a description of this download, to be displayed in notifications (if enabled)
497 * @return this object
498 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700499 public Request setDescription(CharSequence description) {
Steve Howarda2709362010-07-02 17:12:48 -0700500 mDescription = description;
501 return this;
502 }
503
504 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700505 * Set the MIME content type of this download. This will override the content type declared
Steve Howarda2709362010-07-02 17:12:48 -0700506 * in the server's response.
Steve Howard4f564cd2010-09-22 15:57:25 -0700507 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7">HTTP/1.1
508 * Media Types</a>
Steve Howarda2709362010-07-02 17:12:48 -0700509 * @return this object
510 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700511 public Request setMimeType(String mimeType) {
512 mMimeType = mimeType;
Steve Howarda2709362010-07-02 17:12:48 -0700513 return this;
514 }
515
516 /**
Steve Howard8e15afe2010-07-28 17:12:40 -0700517 * Control whether a system notification is posted by the download manager while this
518 * download is running. If enabled, the download manager posts notifications about downloads
519 * through the system {@link android.app.NotificationManager}. By default, a notification is
520 * shown.
Steve Howarda2709362010-07-02 17:12:48 -0700521 *
Steve Howard8e15afe2010-07-28 17:12:40 -0700522 * If set to false, this requires the permission
523 * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
524 *
525 * @param show whether the download manager should show a notification for this download.
Steve Howarda2709362010-07-02 17:12:48 -0700526 * @return this object
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700527 * @deprecated use {@link #setNotificationVisibility(int)}
Steve Howarda2709362010-07-02 17:12:48 -0700528 */
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700529 @Deprecated
Steve Howard8e15afe2010-07-28 17:12:40 -0700530 public Request setShowRunningNotification(boolean show) {
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700531 return (show) ? setNotificationVisibility(VISIBILITY_VISIBLE) :
532 setNotificationVisibility(VISIBILITY_HIDDEN);
533 }
534
535 /**
536 * Control whether a system notification is posted by the download manager while this
537 * download is running or when it is completed.
538 * If enabled, the download manager posts notifications about downloads
539 * through the system {@link android.app.NotificationManager}.
540 * By default, a notification is shown only when the download is in progress.
541 *<p>
542 * It can take the following values: {@link #VISIBILITY_HIDDEN},
543 * {@link #VISIBILITY_VISIBLE},
544 * {@link #VISIBILITY_VISIBLE_NOTIFY_COMPLETED}.
545 *<p>
546 * If set to {@link #VISIBILITY_HIDDEN}, this requires the permission
547 * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
548 *
549 * @param visibility the visibility setting value
550 * @return this object
551 */
552 public Request setNotificationVisibility(int visibility) {
553 mNotificationVisibility = visibility;
Steve Howarda2709362010-07-02 17:12:48 -0700554 return this;
555 }
556
Steve Howardb8e07a52010-07-21 14:53:21 -0700557 /**
558 * Restrict the types of networks over which this download may proceed. By default, all
559 * network types are allowed.
560 * @param flags any combination of the NETWORK_* bit flags.
561 * @return this object
562 */
Steve Howarda2709362010-07-02 17:12:48 -0700563 public Request setAllowedNetworkTypes(int flags) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700564 mAllowedNetworkTypes = flags;
565 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700566 }
567
Steve Howardb8e07a52010-07-21 14:53:21 -0700568 /**
569 * Set whether this download may proceed over a roaming connection. By default, roaming is
570 * allowed.
571 * @param allowed whether to allow a roaming connection to be used
572 * @return this object
573 */
Steve Howarda2709362010-07-02 17:12:48 -0700574 public Request setAllowedOverRoaming(boolean allowed) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700575 mRoamingAllowed = allowed;
576 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700577 }
578
579 /**
Steve Howard90fb15a2010-09-09 16:13:41 -0700580 * Set whether this download should be displayed in the system's Downloads UI. True by
581 * default.
582 * @param isVisible whether to display this download in the Downloads UI
583 * @return this object
584 */
585 public Request setVisibleInDownloadsUi(boolean isVisible) {
586 mIsVisibleInDownloadsUi = isVisible;
587 return this;
588 }
589
590 /**
Steve Howarda2709362010-07-02 17:12:48 -0700591 * @return ContentValues to be passed to DownloadProvider.insert()
592 */
Steve Howardb8e07a52010-07-21 14:53:21 -0700593 ContentValues toContentValues(String packageName) {
Steve Howarda2709362010-07-02 17:12:48 -0700594 ContentValues values = new ContentValues();
595 assert mUri != null;
Vasu Norief7e33b2010-10-20 13:26:02 -0700596 values.put(Downloads.Impl.COLUMN_URI, mUri.toString());
Steve Howardb8e07a52010-07-21 14:53:21 -0700597 values.put(Downloads.Impl.COLUMN_IS_PUBLIC_API, true);
Vasu Norief7e33b2010-10-20 13:26:02 -0700598 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE, packageName);
Steve Howarda2709362010-07-02 17:12:48 -0700599
600 if (mDestinationUri != null) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700601 values.put(Downloads.Impl.COLUMN_DESTINATION, Downloads.Impl.DESTINATION_FILE_URI);
602 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, mDestinationUri.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700603 } else {
Vasu Norief7e33b2010-10-20 13:26:02 -0700604 values.put(Downloads.Impl.COLUMN_DESTINATION,
605 Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE);
Steve Howarda2709362010-07-02 17:12:48 -0700606 }
Vasu Nori5be894e2010-11-02 21:55:30 -0700607 // is the file supposed to be media-scannable?
608 values.put(Downloads.Impl.COLUMN_MEDIA_SCANNED, (mScannable) ? 0 : 2);
Steve Howarda2709362010-07-02 17:12:48 -0700609
610 if (!mRequestHeaders.isEmpty()) {
Steve Howardea9147d2010-07-13 19:02:45 -0700611 encodeHttpHeaders(values);
Steve Howarda2709362010-07-02 17:12:48 -0700612 }
613
Vasu Norief7e33b2010-10-20 13:26:02 -0700614 putIfNonNull(values, Downloads.Impl.COLUMN_TITLE, mTitle);
615 putIfNonNull(values, Downloads.Impl.COLUMN_DESCRIPTION, mDescription);
616 putIfNonNull(values, Downloads.Impl.COLUMN_MIME_TYPE, mMimeType);
Steve Howarda2709362010-07-02 17:12:48 -0700617
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700618 values.put(Downloads.Impl.COLUMN_VISIBILITY, mNotificationVisibility);
Steve Howardb8e07a52010-07-21 14:53:21 -0700619 values.put(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES, mAllowedNetworkTypes);
620 values.put(Downloads.Impl.COLUMN_ALLOW_ROAMING, mRoamingAllowed);
Steve Howard90fb15a2010-09-09 16:13:41 -0700621 values.put(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, mIsVisibleInDownloadsUi);
Steve Howardb8e07a52010-07-21 14:53:21 -0700622
Steve Howarda2709362010-07-02 17:12:48 -0700623 return values;
624 }
625
Steve Howardea9147d2010-07-13 19:02:45 -0700626 private void encodeHttpHeaders(ContentValues values) {
627 int index = 0;
Steve Howard4f564cd2010-09-22 15:57:25 -0700628 for (Pair<String, String> header : mRequestHeaders) {
629 String headerString = header.first + ": " + header.second;
Steve Howardea9147d2010-07-13 19:02:45 -0700630 values.put(Downloads.Impl.RequestHeaders.INSERT_KEY_PREFIX + index, headerString);
631 index++;
632 }
633 }
634
Steve Howard4f564cd2010-09-22 15:57:25 -0700635 private void putIfNonNull(ContentValues contentValues, String key, Object value) {
Steve Howarda2709362010-07-02 17:12:48 -0700636 if (value != null) {
Steve Howard4f564cd2010-09-22 15:57:25 -0700637 contentValues.put(key, value.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700638 }
639 }
640 }
641
642 /**
643 * This class may be used to filter download manager queries.
644 */
645 public static class Query {
Steve Howardf054e192010-09-01 18:26:26 -0700646 /**
647 * Constant for use with {@link #orderBy}
648 * @hide
649 */
650 public static final int ORDER_ASCENDING = 1;
651
652 /**
653 * Constant for use with {@link #orderBy}
654 * @hide
655 */
656 public static final int ORDER_DESCENDING = 2;
657
Steve Howard64c48b82010-10-07 17:53:52 -0700658 private long[] mIds = null;
Steve Howarda2709362010-07-02 17:12:48 -0700659 private Integer mStatusFlags = null;
Vasu Norief7e33b2010-10-20 13:26:02 -0700660 private String mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
Steve Howardf054e192010-09-01 18:26:26 -0700661 private int mOrderDirection = ORDER_DESCENDING;
Steve Howard90fb15a2010-09-09 16:13:41 -0700662 private boolean mOnlyIncludeVisibleInDownloadsUi = false;
Steve Howarda2709362010-07-02 17:12:48 -0700663
664 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700665 * Include only the downloads with the given IDs.
Steve Howarda2709362010-07-02 17:12:48 -0700666 * @return this object
667 */
Steve Howard64c48b82010-10-07 17:53:52 -0700668 public Query setFilterById(long... ids) {
669 mIds = ids;
Steve Howarda2709362010-07-02 17:12:48 -0700670 return this;
671 }
672
673 /**
674 * Include only downloads with status matching any the given status flags.
675 * @param flags any combination of the STATUS_* bit flags
676 * @return this object
677 */
678 public Query setFilterByStatus(int flags) {
679 mStatusFlags = flags;
680 return this;
681 }
682
683 /**
Steve Howard90fb15a2010-09-09 16:13:41 -0700684 * Controls whether this query includes downloads not visible in the system's Downloads UI.
685 * @param value if true, this query will only include downloads that should be displayed in
686 * the system's Downloads UI; if false (the default), this query will include
687 * both visible and invisible downloads.
688 * @return this object
689 * @hide
690 */
691 public Query setOnlyIncludeVisibleInDownloadsUi(boolean value) {
692 mOnlyIncludeVisibleInDownloadsUi = value;
693 return this;
694 }
695
696 /**
Steve Howardf054e192010-09-01 18:26:26 -0700697 * Change the sort order of the returned Cursor.
698 *
699 * @param column one of the COLUMN_* constants; currently, only
700 * {@link #COLUMN_LAST_MODIFIED_TIMESTAMP} and {@link #COLUMN_TOTAL_SIZE_BYTES} are
701 * supported.
702 * @param direction either {@link #ORDER_ASCENDING} or {@link #ORDER_DESCENDING}
703 * @return this object
704 * @hide
705 */
706 public Query orderBy(String column, int direction) {
707 if (direction != ORDER_ASCENDING && direction != ORDER_DESCENDING) {
708 throw new IllegalArgumentException("Invalid direction: " + direction);
709 }
710
711 if (column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP)) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700712 mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
Steve Howardf054e192010-09-01 18:26:26 -0700713 } else if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700714 mOrderByColumn = Downloads.Impl.COLUMN_TOTAL_BYTES;
Steve Howardf054e192010-09-01 18:26:26 -0700715 } else {
716 throw new IllegalArgumentException("Cannot order by " + column);
717 }
718 mOrderDirection = direction;
719 return this;
720 }
721
722 /**
Steve Howarda2709362010-07-02 17:12:48 -0700723 * Run this query using the given ContentResolver.
724 * @param projection the projection to pass to ContentResolver.query()
725 * @return the Cursor returned by ContentResolver.query()
726 */
Steve Howardeca77fc2010-09-12 18:49:08 -0700727 Cursor runQuery(ContentResolver resolver, String[] projection, Uri baseUri) {
728 Uri uri = baseUri;
Steve Howard90fb15a2010-09-09 16:13:41 -0700729 List<String> selectionParts = new ArrayList<String>();
Steve Howard64c48b82010-10-07 17:53:52 -0700730 String[] selectionArgs = null;
Steve Howarda2709362010-07-02 17:12:48 -0700731
Steve Howard64c48b82010-10-07 17:53:52 -0700732 if (mIds != null) {
733 selectionParts.add(getWhereClauseForIds(mIds));
734 selectionArgs = getWhereArgsForIds(mIds);
Steve Howarda2709362010-07-02 17:12:48 -0700735 }
736
737 if (mStatusFlags != null) {
738 List<String> parts = new ArrayList<String>();
739 if ((mStatusFlags & STATUS_PENDING) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700740 parts.add(statusClause("=", Downloads.Impl.STATUS_PENDING));
Steve Howarda2709362010-07-02 17:12:48 -0700741 }
742 if ((mStatusFlags & STATUS_RUNNING) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700743 parts.add(statusClause("=", Downloads.Impl.STATUS_RUNNING));
Steve Howarda2709362010-07-02 17:12:48 -0700744 }
745 if ((mStatusFlags & STATUS_PAUSED) != 0) {
Steve Howard3e8c1d32010-09-29 17:03:32 -0700746 parts.add(statusClause("=", Downloads.Impl.STATUS_PAUSED_BY_APP));
747 parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_TO_RETRY));
748 parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_FOR_NETWORK));
749 parts.add(statusClause("=", Downloads.Impl.STATUS_QUEUED_FOR_WIFI));
Steve Howarda2709362010-07-02 17:12:48 -0700750 }
751 if ((mStatusFlags & STATUS_SUCCESSFUL) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700752 parts.add(statusClause("=", Downloads.Impl.STATUS_SUCCESS));
Steve Howarda2709362010-07-02 17:12:48 -0700753 }
754 if ((mStatusFlags & STATUS_FAILED) != 0) {
755 parts.add("(" + statusClause(">=", 400)
756 + " AND " + statusClause("<", 600) + ")");
757 }
Steve Howard90fb15a2010-09-09 16:13:41 -0700758 selectionParts.add(joinStrings(" OR ", parts));
Steve Howarda2709362010-07-02 17:12:48 -0700759 }
Steve Howardf054e192010-09-01 18:26:26 -0700760
Steve Howard90fb15a2010-09-09 16:13:41 -0700761 if (mOnlyIncludeVisibleInDownloadsUi) {
762 selectionParts.add(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI + " != '0'");
763 }
764
Vasu Nori216fa222010-10-12 23:08:13 -0700765 // only return rows which are not marked 'deleted = 1'
766 selectionParts.add(Downloads.Impl.COLUMN_DELETED + " != '1'");
767
Steve Howard90fb15a2010-09-09 16:13:41 -0700768 String selection = joinStrings(" AND ", selectionParts);
Steve Howardf054e192010-09-01 18:26:26 -0700769 String orderDirection = (mOrderDirection == ORDER_ASCENDING ? "ASC" : "DESC");
770 String orderBy = mOrderByColumn + " " + orderDirection;
771
Steve Howard64c48b82010-10-07 17:53:52 -0700772 return resolver.query(uri, projection, selection, selectionArgs, orderBy);
Steve Howarda2709362010-07-02 17:12:48 -0700773 }
774
775 private String joinStrings(String joiner, Iterable<String> parts) {
776 StringBuilder builder = new StringBuilder();
777 boolean first = true;
778 for (String part : parts) {
779 if (!first) {
780 builder.append(joiner);
781 }
782 builder.append(part);
783 first = false;
784 }
785 return builder.toString();
786 }
787
788 private String statusClause(String operator, int value) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700789 return Downloads.Impl.COLUMN_STATUS + operator + "'" + value + "'";
Steve Howarda2709362010-07-02 17:12:48 -0700790 }
791 }
792
793 private ContentResolver mResolver;
Steve Howardb8e07a52010-07-21 14:53:21 -0700794 private String mPackageName;
Steve Howardeca77fc2010-09-12 18:49:08 -0700795 private Uri mBaseUri = Downloads.Impl.CONTENT_URI;
Steve Howarda2709362010-07-02 17:12:48 -0700796
797 /**
798 * @hide
799 */
Steve Howardb8e07a52010-07-21 14:53:21 -0700800 public DownloadManager(ContentResolver resolver, String packageName) {
Steve Howarda2709362010-07-02 17:12:48 -0700801 mResolver = resolver;
Steve Howardb8e07a52010-07-21 14:53:21 -0700802 mPackageName = packageName;
Steve Howarda2709362010-07-02 17:12:48 -0700803 }
804
805 /**
Steve Howardeca77fc2010-09-12 18:49:08 -0700806 * Makes this object access the download provider through /all_downloads URIs rather than
807 * /my_downloads URIs, for clients that have permission to do so.
808 * @hide
809 */
810 public void setAccessAllDownloads(boolean accessAllDownloads) {
811 if (accessAllDownloads) {
812 mBaseUri = Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI;
813 } else {
814 mBaseUri = Downloads.Impl.CONTENT_URI;
815 }
816 }
817
818 /**
Steve Howarda2709362010-07-02 17:12:48 -0700819 * Enqueue a new download. The download will start automatically once the download manager is
820 * ready to execute it and connectivity is available.
821 *
822 * @param request the parameters specifying this download
823 * @return an ID for the download, unique across the system. This ID is used to make future
824 * calls related to this download.
825 */
826 public long enqueue(Request request) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700827 ContentValues values = request.toContentValues(mPackageName);
Vasu Norief7e33b2010-10-20 13:26:02 -0700828 Uri downloadUri = mResolver.insert(Downloads.Impl.CONTENT_URI, values);
Steve Howarda2709362010-07-02 17:12:48 -0700829 long id = Long.parseLong(downloadUri.getLastPathSegment());
830 return id;
831 }
832
833 /**
Vasu Nori216fa222010-10-12 23:08:13 -0700834 * Marks the specified download as 'to be deleted'. This is done when a completed download
835 * is to be removed but the row was stored without enough info to delete the corresponding
836 * metadata from Mediaprovider database. Actual cleanup of this row is done in DownloadService.
837 *
838 * @param ids the IDs of the downloads to be marked 'deleted'
839 * @return the number of downloads actually updated
840 * @hide
841 */
842 public int markRowDeleted(long... ids) {
843 if (ids == null || ids.length == 0) {
844 // called with nothing to remove!
845 throw new IllegalArgumentException("input param 'ids' can't be null");
846 }
847 ContentValues values = new ContentValues();
848 values.put(Downloads.Impl.COLUMN_DELETED, 1);
849 return mResolver.update(mBaseUri, values, getWhereClauseForIds(ids),
850 getWhereArgsForIds(ids));
851 }
852
853 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700854 * Cancel downloads and remove them from the download manager. Each download will be stopped if
Steve Howarda2709362010-07-02 17:12:48 -0700855 * it was running, and it will no longer be accessible through the download manager. If a file
Steve Howard64c48b82010-10-07 17:53:52 -0700856 * was already downloaded to external storage, it will not be deleted.
Steve Howarda2709362010-07-02 17:12:48 -0700857 *
Steve Howard64c48b82010-10-07 17:53:52 -0700858 * @param ids the IDs of the downloads to remove
859 * @return the number of downloads actually removed
Steve Howarda2709362010-07-02 17:12:48 -0700860 */
Steve Howard64c48b82010-10-07 17:53:52 -0700861 public int remove(long... ids) {
Vasu Norie7be6bd2010-10-10 14:58:08 -0700862 if (ids == null || ids.length == 0) {
863 // called with nothing to remove!
864 throw new IllegalArgumentException("input param 'ids' can't be null");
Steve Howarda2709362010-07-02 17:12:48 -0700865 }
Vasu Norie7be6bd2010-10-10 14:58:08 -0700866 return mResolver.delete(mBaseUri, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
Steve Howarda2709362010-07-02 17:12:48 -0700867 }
868
869 /**
870 * Query the download manager about downloads that have been requested.
871 * @param query parameters specifying filters for this query
872 * @return a Cursor over the result set of downloads, with columns consisting of all the
873 * COLUMN_* constants.
874 */
875 public Cursor query(Query query) {
Steve Howardeca77fc2010-09-12 18:49:08 -0700876 Cursor underlyingCursor = query.runQuery(mResolver, UNDERLYING_COLUMNS, mBaseUri);
Steve Howardf054e192010-09-01 18:26:26 -0700877 if (underlyingCursor == null) {
878 return null;
879 }
Steve Howardeca77fc2010-09-12 18:49:08 -0700880 return new CursorTranslator(underlyingCursor, mBaseUri);
Steve Howarda2709362010-07-02 17:12:48 -0700881 }
882
883 /**
884 * Open a downloaded file for reading. The download must have completed.
885 * @param id the ID of the download
886 * @return a read-only {@link ParcelFileDescriptor}
887 * @throws FileNotFoundException if the destination file does not already exist
888 */
889 public ParcelFileDescriptor openDownloadedFile(long id) throws FileNotFoundException {
890 return mResolver.openFileDescriptor(getDownloadUri(id), "r");
891 }
892
893 /**
Vasu Nori5be894e2010-11-02 21:55:30 -0700894 * Returns {@link Uri} for the given downloaded file id, if the file is
895 * downloaded successfully. otherwise, null is returned.
896 *<p>
897 * If the specified downloaded file is in external storage (for example, /sdcard dir),
898 * then it is assumed to be safe for anyone to read and the returned {@link Uri} can be used
899 * by any app to access the downloaded file.
900 *
901 * @param id the id of the downloaded file.
902 * @return the {@link Uri} for the given downloaded file id, if donload was successful. null
903 * otherwise.
904 */
905 public Uri getUriForDownloadedFile(long id) {
906 // to check if the file is in cache, get its destination from the database
907 Query query = new Query().setFilterById(id);
908 Cursor cursor = null;
909 try {
910 cursor = query(query);
911 if (cursor == null) {
912 return null;
913 }
914 while (cursor.moveToFirst()) {
915 int status = cursor.getInt(cursor.getColumnIndexOrThrow(
916 DownloadManager.COLUMN_STATUS));
917 if (DownloadManager.STATUS_SUCCESSFUL == status) {
918 int indx = cursor.getColumnIndexOrThrow(
919 Downloads.Impl.COLUMN_DESTINATION);
920 int destination = cursor.getInt(indx);
921 // TODO: if we ever add API to DownloadManager to let the caller specify
922 // non-external storage for a donloaded file, then the following code
923 // should also check for that destination.
924 if (destination == Downloads.Impl.DESTINATION_CACHE_PARTITION ||
925 destination == Downloads.Impl.DESTINATION_CACHE_PARTITION_NOROAMING ||
926 destination == Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE) {
927 // return private uri
928 return ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI, id);
929 } else {
930 // return public uri
931 return ContentUris.withAppendedId(
932 Downloads.Impl.PUBLICLY_ACCESSIBLE_DOWNLOADS_URI, id);
933 }
934 }
935 }
936 } finally {
937 if (cursor != null) {
938 cursor.close();
939 }
940 }
941 // downloaded file not found or its status is not 'successfully completed'
942 return null;
943 }
944
945 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700946 * Restart the given downloads, which must have already completed (successfully or not). This
Steve Howard90fb15a2010-09-09 16:13:41 -0700947 * method will only work when called from within the download manager's process.
Steve Howard64c48b82010-10-07 17:53:52 -0700948 * @param ids the IDs of the downloads
Steve Howard90fb15a2010-09-09 16:13:41 -0700949 * @hide
950 */
Steve Howard64c48b82010-10-07 17:53:52 -0700951 public void restartDownload(long... ids) {
952 Cursor cursor = query(new Query().setFilterById(ids));
Steve Howard90fb15a2010-09-09 16:13:41 -0700953 try {
Steve Howard64c48b82010-10-07 17:53:52 -0700954 for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
955 int status = cursor.getInt(cursor.getColumnIndex(COLUMN_STATUS));
956 if (status != STATUS_SUCCESSFUL && status != STATUS_FAILED) {
957 throw new IllegalArgumentException("Cannot restart incomplete download: "
958 + cursor.getLong(cursor.getColumnIndex(COLUMN_ID)));
959 }
Steve Howard90fb15a2010-09-09 16:13:41 -0700960 }
961 } finally {
962 cursor.close();
963 }
964
965 ContentValues values = new ContentValues();
966 values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, 0);
967 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, -1);
968 values.putNull(Downloads.Impl._DATA);
969 values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING);
Steve Howard64c48b82010-10-07 17:53:52 -0700970 mResolver.update(mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
Steve Howard90fb15a2010-09-09 16:13:41 -0700971 }
972
973 /**
Steve Howarda2709362010-07-02 17:12:48 -0700974 * Get the DownloadProvider URI for the download with the given ID.
975 */
Steve Howardeca77fc2010-09-12 18:49:08 -0700976 Uri getDownloadUri(long id) {
977 return ContentUris.withAppendedId(mBaseUri, id);
Steve Howarda2709362010-07-02 17:12:48 -0700978 }
979
980 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700981 * Get a parameterized SQL WHERE clause to select a bunch of IDs.
982 */
983 static String getWhereClauseForIds(long[] ids) {
984 StringBuilder whereClause = new StringBuilder();
Vasu Norie7be6bd2010-10-10 14:58:08 -0700985 whereClause.append("(");
Steve Howard64c48b82010-10-07 17:53:52 -0700986 for (int i = 0; i < ids.length; i++) {
987 if (i > 0) {
Vasu Norie7be6bd2010-10-10 14:58:08 -0700988 whereClause.append("OR ");
Steve Howard64c48b82010-10-07 17:53:52 -0700989 }
Vasu Norie7be6bd2010-10-10 14:58:08 -0700990 whereClause.append(Downloads.Impl._ID);
991 whereClause.append(" = ? ");
Steve Howard64c48b82010-10-07 17:53:52 -0700992 }
993 whereClause.append(")");
994 return whereClause.toString();
995 }
996
997 /**
998 * Get the selection args for a clause returned by {@link #getWhereClauseForIds(long[])}.
999 */
1000 static String[] getWhereArgsForIds(long[] ids) {
1001 String[] whereArgs = new String[ids.length];
1002 for (int i = 0; i < ids.length; i++) {
1003 whereArgs[i] = Long.toString(ids[i]);
1004 }
1005 return whereArgs;
1006 }
1007
1008 /**
Steve Howarda2709362010-07-02 17:12:48 -07001009 * This class wraps a cursor returned by DownloadProvider -- the "underlying cursor" -- and
1010 * presents a different set of columns, those defined in the DownloadManager.COLUMN_* constants.
1011 * Some columns correspond directly to underlying values while others are computed from
1012 * underlying data.
1013 */
1014 private static class CursorTranslator extends CursorWrapper {
Steve Howardeca77fc2010-09-12 18:49:08 -07001015 private Uri mBaseUri;
1016
1017 public CursorTranslator(Cursor cursor, Uri baseUri) {
Steve Howarda2709362010-07-02 17:12:48 -07001018 super(cursor);
Steve Howardeca77fc2010-09-12 18:49:08 -07001019 mBaseUri = baseUri;
Steve Howarda2709362010-07-02 17:12:48 -07001020 }
1021
1022 @Override
1023 public int getColumnIndex(String columnName) {
1024 return Arrays.asList(COLUMNS).indexOf(columnName);
1025 }
1026
1027 @Override
1028 public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException {
1029 int index = getColumnIndex(columnName);
1030 if (index == -1) {
Steve Howardf054e192010-09-01 18:26:26 -07001031 throw new IllegalArgumentException("No such column: " + columnName);
Steve Howarda2709362010-07-02 17:12:48 -07001032 }
1033 return index;
1034 }
1035
1036 @Override
1037 public String getColumnName(int columnIndex) {
1038 int numColumns = COLUMNS.length;
1039 if (columnIndex < 0 || columnIndex >= numColumns) {
1040 throw new IllegalArgumentException("Invalid column index " + columnIndex + ", "
1041 + numColumns + " columns exist");
1042 }
1043 return COLUMNS[columnIndex];
1044 }
1045
1046 @Override
1047 public String[] getColumnNames() {
1048 String[] returnColumns = new String[COLUMNS.length];
1049 System.arraycopy(COLUMNS, 0, returnColumns, 0, COLUMNS.length);
1050 return returnColumns;
1051 }
1052
1053 @Override
1054 public int getColumnCount() {
1055 return COLUMNS.length;
1056 }
1057
1058 @Override
1059 public byte[] getBlob(int columnIndex) {
1060 throw new UnsupportedOperationException();
1061 }
1062
1063 @Override
1064 public double getDouble(int columnIndex) {
1065 return getLong(columnIndex);
1066 }
1067
1068 private boolean isLongColumn(String column) {
1069 return LONG_COLUMNS.contains(column);
1070 }
1071
1072 @Override
1073 public float getFloat(int columnIndex) {
1074 return (float) getDouble(columnIndex);
1075 }
1076
1077 @Override
1078 public int getInt(int columnIndex) {
1079 return (int) getLong(columnIndex);
1080 }
1081
1082 @Override
1083 public long getLong(int columnIndex) {
1084 return translateLong(getColumnName(columnIndex));
1085 }
1086
1087 @Override
1088 public short getShort(int columnIndex) {
1089 return (short) getLong(columnIndex);
1090 }
1091
1092 @Override
1093 public String getString(int columnIndex) {
1094 return translateString(getColumnName(columnIndex));
1095 }
1096
1097 private String translateString(String column) {
1098 if (isLongColumn(column)) {
1099 return Long.toString(translateLong(column));
1100 }
1101 if (column.equals(COLUMN_TITLE)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001102 return getUnderlyingString(Downloads.Impl.COLUMN_TITLE);
Steve Howarda2709362010-07-02 17:12:48 -07001103 }
1104 if (column.equals(COLUMN_DESCRIPTION)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001105 return getUnderlyingString(Downloads.Impl.COLUMN_DESCRIPTION);
Steve Howarda2709362010-07-02 17:12:48 -07001106 }
1107 if (column.equals(COLUMN_URI)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001108 return getUnderlyingString(Downloads.Impl.COLUMN_URI);
Steve Howarda2709362010-07-02 17:12:48 -07001109 }
1110 if (column.equals(COLUMN_MEDIA_TYPE)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001111 return getUnderlyingString(Downloads.Impl.COLUMN_MIME_TYPE);
Steve Howarda2709362010-07-02 17:12:48 -07001112 }
Doug Zongkeree04af32010-10-08 13:42:16 -07001113 if (column.equals(COLUMN_LOCAL_FILENAME)) {
1114 return getUnderlyingString(Downloads.Impl._DATA);
1115 }
Vasu Nori216fa222010-10-12 23:08:13 -07001116 if (column.equals(COLUMN_MEDIAPROVIDER_URI)) {
1117 return getUnderlyingString(Downloads.Impl.COLUMN_MEDIAPROVIDER_URI);
1118 }
Steve Howard8651bd52010-08-03 12:35:32 -07001119
Steve Howarda2709362010-07-02 17:12:48 -07001120 assert column.equals(COLUMN_LOCAL_URI);
Steve Howardeca77fc2010-09-12 18:49:08 -07001121 return getLocalUri();
1122 }
1123
1124 private String getLocalUri() {
Steve Howardeca77fc2010-09-12 18:49:08 -07001125 long destinationType = getUnderlyingLong(Downloads.Impl.COLUMN_DESTINATION);
1126 if (destinationType == Downloads.Impl.DESTINATION_FILE_URI) {
Steve Howarda9e87c92010-09-16 12:02:03 -07001127 // return client-provided file URI for external download
1128 return getUnderlyingString(Downloads.Impl.COLUMN_FILE_NAME_HINT);
Steve Howardeca77fc2010-09-12 18:49:08 -07001129 }
1130
Steve Howardbb0d23b2010-09-22 18:56:29 -07001131 if (destinationType == Downloads.Impl.DESTINATION_EXTERNAL) {
1132 // return stored destination for legacy external download
Steve Howard99047d72010-09-29 17:41:37 -07001133 String localPath = getUnderlyingString(Downloads.Impl._DATA);
1134 if (localPath == null) {
1135 return null;
1136 }
1137 return Uri.fromFile(new File(localPath)).toString();
Steve Howardbb0d23b2010-09-22 18:56:29 -07001138 }
1139
Steve Howardeca77fc2010-09-12 18:49:08 -07001140 // return content URI for cache download
1141 long downloadId = getUnderlyingLong(Downloads.Impl._ID);
1142 return ContentUris.withAppendedId(mBaseUri, downloadId).toString();
Steve Howarda2709362010-07-02 17:12:48 -07001143 }
1144
1145 private long translateLong(String column) {
1146 if (!isLongColumn(column)) {
1147 // mimic behavior of underlying cursor -- most likely, throw NumberFormatException
1148 return Long.valueOf(translateString(column));
1149 }
1150
1151 if (column.equals(COLUMN_ID)) {
1152 return getUnderlyingLong(Downloads.Impl._ID);
1153 }
1154 if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001155 return getUnderlyingLong(Downloads.Impl.COLUMN_TOTAL_BYTES);
Steve Howarda2709362010-07-02 17:12:48 -07001156 }
1157 if (column.equals(COLUMN_STATUS)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001158 return translateStatus((int) getUnderlyingLong(Downloads.Impl.COLUMN_STATUS));
Steve Howarda2709362010-07-02 17:12:48 -07001159 }
Steve Howard3e8c1d32010-09-29 17:03:32 -07001160 if (column.equals(COLUMN_REASON)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001161 return getReason((int) getUnderlyingLong(Downloads.Impl.COLUMN_STATUS));
Steve Howarda2709362010-07-02 17:12:48 -07001162 }
1163 if (column.equals(COLUMN_BYTES_DOWNLOADED_SO_FAR)) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001164 return getUnderlyingLong(Downloads.Impl.COLUMN_CURRENT_BYTES);
Steve Howarda2709362010-07-02 17:12:48 -07001165 }
Vasu Nori5be894e2010-11-02 21:55:30 -07001166 if (column.equals(Downloads.Impl.COLUMN_DESTINATION)) {
1167 return getUnderlyingLong(Downloads.Impl.COLUMN_DESTINATION);
1168 }
Steve Howardadcb6972010-07-12 17:09:25 -07001169 assert column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP);
Vasu Norief7e33b2010-10-20 13:26:02 -07001170 return getUnderlyingLong(Downloads.Impl.COLUMN_LAST_MODIFICATION);
Steve Howarda2709362010-07-02 17:12:48 -07001171 }
1172
Steve Howard3e8c1d32010-09-29 17:03:32 -07001173 private long getReason(int status) {
1174 switch (translateStatus(status)) {
1175 case STATUS_FAILED:
1176 return getErrorCode(status);
1177
1178 case STATUS_PAUSED:
1179 return getPausedReason(status);
1180
1181 default:
1182 return 0; // arbitrary value when status is not an error
Steve Howarda2709362010-07-02 17:12:48 -07001183 }
Steve Howard3e8c1d32010-09-29 17:03:32 -07001184 }
1185
1186 private long getPausedReason(int status) {
1187 switch (status) {
1188 case Downloads.Impl.STATUS_WAITING_TO_RETRY:
1189 return PAUSED_WAITING_TO_RETRY;
1190
1191 case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
1192 return PAUSED_WAITING_FOR_NETWORK;
1193
1194 case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
1195 return PAUSED_QUEUED_FOR_WIFI;
1196
1197 default:
1198 return PAUSED_UNKNOWN;
1199 }
1200 }
1201
1202 private long getErrorCode(int status) {
Steve Howard33bbd122010-08-02 17:51:29 -07001203 if ((400 <= status && status < Downloads.Impl.MIN_ARTIFICIAL_ERROR_STATUS)
1204 || (500 <= status && status < 600)) {
Steve Howarda2709362010-07-02 17:12:48 -07001205 // HTTP status code
1206 return status;
1207 }
1208
1209 switch (status) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001210 case Downloads.Impl.STATUS_FILE_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001211 return ERROR_FILE_ERROR;
1212
Vasu Norief7e33b2010-10-20 13:26:02 -07001213 case Downloads.Impl.STATUS_UNHANDLED_HTTP_CODE:
1214 case Downloads.Impl.STATUS_UNHANDLED_REDIRECT:
Steve Howarda2709362010-07-02 17:12:48 -07001215 return ERROR_UNHANDLED_HTTP_CODE;
1216
Vasu Norief7e33b2010-10-20 13:26:02 -07001217 case Downloads.Impl.STATUS_HTTP_DATA_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001218 return ERROR_HTTP_DATA_ERROR;
1219
Vasu Norief7e33b2010-10-20 13:26:02 -07001220 case Downloads.Impl.STATUS_TOO_MANY_REDIRECTS:
Steve Howarda2709362010-07-02 17:12:48 -07001221 return ERROR_TOO_MANY_REDIRECTS;
1222
Vasu Norief7e33b2010-10-20 13:26:02 -07001223 case Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001224 return ERROR_INSUFFICIENT_SPACE;
1225
Vasu Norief7e33b2010-10-20 13:26:02 -07001226 case Downloads.Impl.STATUS_DEVICE_NOT_FOUND_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001227 return ERROR_DEVICE_NOT_FOUND;
1228
Steve Howard33bbd122010-08-02 17:51:29 -07001229 case Downloads.Impl.STATUS_CANNOT_RESUME:
1230 return ERROR_CANNOT_RESUME;
1231
Steve Howarda9e87c92010-09-16 12:02:03 -07001232 case Downloads.Impl.STATUS_FILE_ALREADY_EXISTS_ERROR:
1233 return ERROR_FILE_ALREADY_EXISTS;
1234
Steve Howarda2709362010-07-02 17:12:48 -07001235 default:
1236 return ERROR_UNKNOWN;
1237 }
1238 }
1239
1240 private long getUnderlyingLong(String column) {
1241 return super.getLong(super.getColumnIndex(column));
1242 }
1243
1244 private String getUnderlyingString(String column) {
1245 return super.getString(super.getColumnIndex(column));
1246 }
1247
Steve Howard3e8c1d32010-09-29 17:03:32 -07001248 private int translateStatus(int status) {
Steve Howarda2709362010-07-02 17:12:48 -07001249 switch (status) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001250 case Downloads.Impl.STATUS_PENDING:
Steve Howarda2709362010-07-02 17:12:48 -07001251 return STATUS_PENDING;
1252
Vasu Norief7e33b2010-10-20 13:26:02 -07001253 case Downloads.Impl.STATUS_RUNNING:
Steve Howarda2709362010-07-02 17:12:48 -07001254 return STATUS_RUNNING;
1255
Steve Howard3e8c1d32010-09-29 17:03:32 -07001256 case Downloads.Impl.STATUS_PAUSED_BY_APP:
1257 case Downloads.Impl.STATUS_WAITING_TO_RETRY:
1258 case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
1259 case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
Steve Howarda2709362010-07-02 17:12:48 -07001260 return STATUS_PAUSED;
1261
Vasu Norief7e33b2010-10-20 13:26:02 -07001262 case Downloads.Impl.STATUS_SUCCESS:
Steve Howarda2709362010-07-02 17:12:48 -07001263 return STATUS_SUCCESSFUL;
1264
1265 default:
Vasu Norief7e33b2010-10-20 13:26:02 -07001266 assert Downloads.Impl.isStatusError(status);
Steve Howarda2709362010-07-02 17:12:48 -07001267 return STATUS_FAILED;
1268 }
1269 }
1270 }
1271}