blob: 09a21f8ba0cd8f489a3a7b2a1700d6f473f559ae [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;
Steve Howarda2709362010-07-02 17:12:48 -070036import java.util.List;
Steve Howarda2709362010-07-02 17:12:48 -070037
38/**
39 * The download manager is a system service that handles long-running HTTP downloads. Clients may
40 * request that a URI be downloaded to a particular destination file. The download manager will
41 * conduct the download in the background, taking care of HTTP interactions and retrying downloads
42 * after failures or across connectivity changes and system reboots.
43 *
44 * Instances of this class should be obtained through
45 * {@link android.content.Context#getSystemService(String)} by passing
46 * {@link android.content.Context#DOWNLOAD_SERVICE}.
Steve Howard610c4352010-09-30 18:30:04 -070047 *
48 * Apps that request downloads through this API should register a broadcast receiver for
49 * {@link #ACTION_NOTIFICATION_CLICKED} to appropriately handle when the user clicks on a running
50 * download in a notification or from the downloads UI.
Steve Howarda2709362010-07-02 17:12:48 -070051 */
52public class DownloadManager {
Vasu Norie7be6bd2010-10-10 14:58:08 -070053 private static final String TAG = "DownloadManager";
54
Steve Howarda2709362010-07-02 17:12:48 -070055 /**
56 * An identifier for a particular download, unique across the system. Clients use this ID to
57 * make subsequent calls related to the download.
58 */
Vasu Norief7e33b2010-10-20 13:26:02 -070059 public final static String COLUMN_ID = Downloads.Impl._ID;
Steve Howarda2709362010-07-02 17:12:48 -070060
61 /**
Steve Howard8651bd52010-08-03 12:35:32 -070062 * The client-supplied title for this download. This will be displayed in system notifications.
63 * Defaults to the empty string.
Steve Howarda2709362010-07-02 17:12:48 -070064 */
Vasu Norief7e33b2010-10-20 13:26:02 -070065 public final static String COLUMN_TITLE = Downloads.Impl.COLUMN_TITLE;
Steve Howarda2709362010-07-02 17:12:48 -070066
67 /**
68 * The client-supplied description of this download. This will be displayed in system
Steve Howard8651bd52010-08-03 12:35:32 -070069 * notifications. Defaults to the empty string.
Steve Howarda2709362010-07-02 17:12:48 -070070 */
Vasu Norief7e33b2010-10-20 13:26:02 -070071 public final static String COLUMN_DESCRIPTION = Downloads.Impl.COLUMN_DESCRIPTION;
Steve Howarda2709362010-07-02 17:12:48 -070072
73 /**
74 * URI to be downloaded.
75 */
Vasu Norief7e33b2010-10-20 13:26:02 -070076 public final static String COLUMN_URI = Downloads.Impl.COLUMN_URI;
Steve Howarda2709362010-07-02 17:12:48 -070077
78 /**
Steve Howard8651bd52010-08-03 12:35:32 -070079 * Internet Media Type of the downloaded file. If no value is provided upon creation, this will
80 * initially be null and will be filled in based on the server's response once the download has
81 * started.
Steve Howarda2709362010-07-02 17:12:48 -070082 *
83 * @see <a href="http://www.ietf.org/rfc/rfc1590.txt">RFC 1590, defining Media Types</a>
84 */
85 public final static String COLUMN_MEDIA_TYPE = "media_type";
86
87 /**
Steve Howard8651bd52010-08-03 12:35:32 -070088 * Total size of the download in bytes. This will initially be -1 and will be filled in once
89 * the download starts.
Steve Howarda2709362010-07-02 17:12:48 -070090 */
91 public final static String COLUMN_TOTAL_SIZE_BYTES = "total_size";
92
93 /**
94 * Uri where downloaded file will be stored. If a destination is supplied by client, that URI
Steve Howard8651bd52010-08-03 12:35:32 -070095 * will be used here. Otherwise, the value will initially be null and will be filled in with a
96 * generated URI once the download has started.
Steve Howarda2709362010-07-02 17:12:48 -070097 */
98 public final static String COLUMN_LOCAL_URI = "local_uri";
99
100 /**
Doug Zongkeree04af32010-10-08 13:42:16 -0700101 * The pathname of the file where the download is stored.
102 */
103 public final static String COLUMN_LOCAL_FILENAME = "local_filename";
104
105 /**
Steve Howarda2709362010-07-02 17:12:48 -0700106 * Current status of the download, as one of the STATUS_* constants.
107 */
Vasu Norief7e33b2010-10-20 13:26:02 -0700108 public final static String COLUMN_STATUS = Downloads.Impl.COLUMN_STATUS;
Steve Howarda2709362010-07-02 17:12:48 -0700109
110 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700111 * Provides more detail on the status of the download. Its meaning depends on the value of
112 * {@link #COLUMN_STATUS}.
Steve Howarda2709362010-07-02 17:12:48 -0700113 *
Steve Howard3e8c1d32010-09-29 17:03:32 -0700114 * When {@link #COLUMN_STATUS} is {@link #STATUS_FAILED}, this indicates the type of error that
115 * occurred. If an HTTP error occurred, this will hold the HTTP status code as defined in RFC
116 * 2616. Otherwise, it will hold one of the ERROR_* constants.
117 *
118 * When {@link #COLUMN_STATUS} is {@link #STATUS_PAUSED}, this indicates why the download is
119 * paused. It will hold one of the PAUSED_* constants.
120 *
121 * If {@link #COLUMN_STATUS} is neither {@link #STATUS_FAILED} nor {@link #STATUS_PAUSED}, this
122 * column's value is undefined.
Steve Howarda2709362010-07-02 17:12:48 -0700123 *
124 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1.1">RFC 2616
125 * status codes</a>
126 */
Steve Howard3e8c1d32010-09-29 17:03:32 -0700127 public final static String COLUMN_REASON = "reason";
Steve Howarda2709362010-07-02 17:12:48 -0700128
129 /**
130 * Number of bytes download so far.
131 */
132 public final static String COLUMN_BYTES_DOWNLOADED_SO_FAR = "bytes_so_far";
133
134 /**
Steve Howardadcb6972010-07-12 17:09:25 -0700135 * Timestamp when the download was last modified, in {@link System#currentTimeMillis
Steve Howarda2709362010-07-02 17:12:48 -0700136 * System.currentTimeMillis()} (wall clock time in UTC).
137 */
Steve Howardadcb6972010-07-12 17:09:25 -0700138 public final static String COLUMN_LAST_MODIFIED_TIMESTAMP = "last_modified_timestamp";
Steve Howarda2709362010-07-02 17:12:48 -0700139
Vasu Nori216fa222010-10-12 23:08:13 -0700140 /**
141 * The URI to the corresponding entry in MediaProvider for this downloaded entry. It is
142 * used to delete the entries from MediaProvider database when it is deleted from the
143 * downloaded list.
144 */
Vasu Norief7e33b2010-10-20 13:26:02 -0700145 public static final String COLUMN_MEDIAPROVIDER_URI = Downloads.Impl.COLUMN_MEDIAPROVIDER_URI;
Steve Howarda2709362010-07-02 17:12:48 -0700146
147 /**
148 * Value of {@link #COLUMN_STATUS} when the download is waiting to start.
149 */
150 public final static int STATUS_PENDING = 1 << 0;
151
152 /**
153 * Value of {@link #COLUMN_STATUS} when the download is currently running.
154 */
155 public final static int STATUS_RUNNING = 1 << 1;
156
157 /**
158 * Value of {@link #COLUMN_STATUS} when the download is waiting to retry or resume.
159 */
160 public final static int STATUS_PAUSED = 1 << 2;
161
162 /**
163 * Value of {@link #COLUMN_STATUS} when the download has successfully completed.
164 */
165 public final static int STATUS_SUCCESSFUL = 1 << 3;
166
167 /**
168 * Value of {@link #COLUMN_STATUS} when the download has failed (and will not be retried).
169 */
170 public final static int STATUS_FAILED = 1 << 4;
171
172
173 /**
174 * Value of COLUMN_ERROR_CODE when the download has completed with an error that doesn't fit
175 * under any other error code.
176 */
177 public final static int ERROR_UNKNOWN = 1000;
178
179 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700180 * Value of {@link #COLUMN_REASON} when a storage issue arises which doesn't fit under any
Steve Howarda2709362010-07-02 17:12:48 -0700181 * other error code. Use the more specific {@link #ERROR_INSUFFICIENT_SPACE} and
182 * {@link #ERROR_DEVICE_NOT_FOUND} when appropriate.
183 */
184 public final static int ERROR_FILE_ERROR = 1001;
185
186 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700187 * Value of {@link #COLUMN_REASON} when an HTTP code was received that download manager
Steve Howarda2709362010-07-02 17:12:48 -0700188 * can't handle.
189 */
190 public final static int ERROR_UNHANDLED_HTTP_CODE = 1002;
191
192 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700193 * Value of {@link #COLUMN_REASON} when an error receiving or processing data occurred at
Steve Howarda2709362010-07-02 17:12:48 -0700194 * the HTTP level.
195 */
196 public final static int ERROR_HTTP_DATA_ERROR = 1004;
197
198 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700199 * Value of {@link #COLUMN_REASON} when there were too many redirects.
Steve Howarda2709362010-07-02 17:12:48 -0700200 */
201 public final static int ERROR_TOO_MANY_REDIRECTS = 1005;
202
203 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700204 * Value of {@link #COLUMN_REASON} when there was insufficient storage space. Typically,
Steve Howarda2709362010-07-02 17:12:48 -0700205 * this is because the SD card is full.
206 */
207 public final static int ERROR_INSUFFICIENT_SPACE = 1006;
208
209 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700210 * Value of {@link #COLUMN_REASON} when no external storage device was found. Typically,
Steve Howarda2709362010-07-02 17:12:48 -0700211 * this is because the SD card is not mounted.
212 */
213 public final static int ERROR_DEVICE_NOT_FOUND = 1007;
214
Steve Howardb8e07a52010-07-21 14:53:21 -0700215 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700216 * Value of {@link #COLUMN_REASON} when some possibly transient error occurred but we can't
Steve Howard33bbd122010-08-02 17:51:29 -0700217 * resume the download.
218 */
219 public final static int ERROR_CANNOT_RESUME = 1008;
220
221 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700222 * Value of {@link #COLUMN_REASON} when the requested destination file already exists (the
Steve Howarda9e87c92010-09-16 12:02:03 -0700223 * download manager will not overwrite an existing file).
224 */
225 public final static int ERROR_FILE_ALREADY_EXISTS = 1009;
226
227 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700228 * Value of {@link #COLUMN_REASON} when the download is paused because some network error
229 * occurred and the download manager is waiting before retrying the request.
230 */
231 public final static int PAUSED_WAITING_TO_RETRY = 1;
232
233 /**
234 * Value of {@link #COLUMN_REASON} when the download is waiting for network connectivity to
235 * proceed.
236 */
237 public final static int PAUSED_WAITING_FOR_NETWORK = 2;
238
239 /**
240 * Value of {@link #COLUMN_REASON} when the download exceeds a size limit for downloads over
241 * the mobile network and the download manager is waiting for a Wi-Fi connection to proceed.
242 */
243 public final static int PAUSED_QUEUED_FOR_WIFI = 3;
244
245 /**
246 * Value of {@link #COLUMN_REASON} when the download is paused for some other reason.
247 */
248 public final static int PAUSED_UNKNOWN = 4;
249
250 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700251 * Broadcast intent action sent by the download manager when a download completes.
252 */
253 public final static String ACTION_DOWNLOAD_COMPLETE = "android.intent.action.DOWNLOAD_COMPLETE";
254
255 /**
Steve Howard610c4352010-09-30 18:30:04 -0700256 * Broadcast intent action sent by the download manager when the user clicks on a running
257 * download, either from a system notification or from the downloads UI.
Steve Howardb8e07a52010-07-21 14:53:21 -0700258 */
259 public final static String ACTION_NOTIFICATION_CLICKED =
260 "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED";
261
262 /**
Steve Howarde78fc182010-09-24 14:59:36 -0700263 * Intent action to launch an activity to display all downloads.
264 */
265 public final static String ACTION_VIEW_DOWNLOADS = "android.intent.action.VIEW_DOWNLOADS";
266
267 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700268 * Intent extra included with {@link #ACTION_DOWNLOAD_COMPLETE} intents, indicating the ID (as a
269 * long) of the download that just completed.
270 */
271 public static final String EXTRA_DOWNLOAD_ID = "extra_download_id";
Steve Howarda2709362010-07-02 17:12:48 -0700272
Vasu Nori71b8c232010-10-27 15:22:19 -0700273 /**
274 * When clicks on multiple notifications are received, the following
275 * provides an array of download ids corresponding to the download notification that was
276 * clicked. It can be retrieved by the receiver of this
277 * Intent using {@link android.content.Intent#getLongArrayExtra(String)}.
278 */
279 public static final String EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS = "extra_click_download_ids";
280
Vasu Norie16c43b2010-11-06 18:48:08 -0700281 /**
282 * columns to request from DownloadProvider.
283 * @hide
284 */
285 public static final String[] UNDERLYING_COLUMNS = new String[] {
Steve Howarda2709362010-07-02 17:12:48 -0700286 Downloads.Impl._ID,
Vasu Norie69924f2010-11-15 13:10:11 -0800287 Downloads.Impl._DATA + " AS " + COLUMN_LOCAL_FILENAME,
Vasu Nori216fa222010-10-12 23:08:13 -0700288 Downloads.Impl.COLUMN_MEDIAPROVIDER_URI,
Vasu Nori5be894e2010-11-02 21:55:30 -0700289 Downloads.Impl.COLUMN_DESTINATION,
Vasu Norief7e33b2010-10-20 13:26:02 -0700290 Downloads.Impl.COLUMN_TITLE,
291 Downloads.Impl.COLUMN_DESCRIPTION,
292 Downloads.Impl.COLUMN_URI,
Vasu Norief7e33b2010-10-20 13:26:02 -0700293 Downloads.Impl.COLUMN_STATUS,
Steve Howarda9e87c92010-09-16 12:02:03 -0700294 Downloads.Impl.COLUMN_FILE_NAME_HINT,
Vasu Norie16c43b2010-11-06 18:48:08 -0700295 Downloads.Impl.COLUMN_MIME_TYPE + " AS " + COLUMN_MEDIA_TYPE,
296 Downloads.Impl.COLUMN_TOTAL_BYTES + " AS " + COLUMN_TOTAL_SIZE_BYTES,
297 Downloads.Impl.COLUMN_LAST_MODIFICATION + " AS " + COLUMN_LAST_MODIFIED_TIMESTAMP,
298 Downloads.Impl.COLUMN_CURRENT_BYTES + " AS " + COLUMN_BYTES_DOWNLOADED_SO_FAR,
299 /* add the following 'computed' columns to the cursor.
300 * they are not 'returned' by the database, but their inclusion
301 * eliminates need to have lot of methods in CursorTranslator
302 */
303 "'placeholder' AS " + COLUMN_LOCAL_URI,
304 "'placeholder' AS " + COLUMN_REASON
Steve Howarda2709362010-07-02 17:12:48 -0700305 };
306
Steve Howarda2709362010-07-02 17:12:48 -0700307 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700308 * This class contains all the information necessary to request a new download. The URI is the
Steve Howarda2709362010-07-02 17:12:48 -0700309 * only required parameter.
Steve Howard4f564cd2010-09-22 15:57:25 -0700310 *
311 * Note that the default download destination is a shared volume where the system might delete
312 * your file if it needs to reclaim space for system use. If this is a problem, use a location
313 * on external storage (see {@link #setDestinationUri(Uri)}.
Steve Howarda2709362010-07-02 17:12:48 -0700314 */
315 public static class Request {
316 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700317 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
318 * {@link ConnectivityManager#TYPE_MOBILE}.
319 */
320 public static final int NETWORK_MOBILE = 1 << 0;
Steve Howarda2709362010-07-02 17:12:48 -0700321
Steve Howardb8e07a52010-07-21 14:53:21 -0700322 /**
323 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
324 * {@link ConnectivityManager#TYPE_WIFI}.
325 */
326 public static final int NETWORK_WIFI = 1 << 1;
327
Steve Howardb8e07a52010-07-21 14:53:21 -0700328 private Uri mUri;
329 private Uri mDestinationUri;
Steve Howard4f564cd2010-09-22 15:57:25 -0700330 private List<Pair<String, String>> mRequestHeaders = new ArrayList<Pair<String, String>>();
331 private CharSequence mTitle;
332 private CharSequence mDescription;
Steve Howard4f564cd2010-09-22 15:57:25 -0700333 private String mMimeType;
Steve Howardb8e07a52010-07-21 14:53:21 -0700334 private boolean mRoamingAllowed = true;
335 private int mAllowedNetworkTypes = ~0; // default to all network types allowed
Steve Howard90fb15a2010-09-09 16:13:41 -0700336 private boolean mIsVisibleInDownloadsUi = true;
Vasu Nori5be894e2010-11-02 21:55:30 -0700337 private boolean mScannable = false;
Vasu Nori1cde3fb2010-11-05 11:02:52 -0700338 /** if a file is designated as a MediaScanner scannable file, the following value is
339 * stored in the database column {@link Downloads.Impl#COLUMN_MEDIA_SCANNED}.
340 */
341 private static final int SCANNABLE_VALUE_YES = 0;
342 // value of 1 is stored in the above column by DownloadProvider after it is scanned by
343 // MediaScanner
344 /** if a file is designated as a file that should not be scanned by MediaScanner,
345 * the following value is stored in the database column
346 * {@link Downloads.Impl#COLUMN_MEDIA_SCANNED}.
347 */
348 private static final int SCANNABLE_VALUE_NO = 2;
Steve Howarda2709362010-07-02 17:12:48 -0700349
350 /**
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700351 * This download is visible but only shows in the notifications
352 * while it's in progress.
353 */
354 public static final int VISIBILITY_VISIBLE = 0;
355
356 /**
357 * This download is visible and shows in the notifications while
358 * in progress and after completion.
359 */
360 public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED = 1;
361
362 /**
363 * This download doesn't show in the UI or in the notifications.
364 */
365 public static final int VISIBILITY_HIDDEN = 2;
366
367 /** can take any of the following values: {@link #VISIBILITY_HIDDEN}
368 * {@link #VISIBILITY_VISIBLE_NOTIFY_COMPLETED}, {@link #VISIBILITY_VISIBLE}
369 */
370 private int mNotificationVisibility = VISIBILITY_VISIBLE;
371
372 /**
Steve Howarda2709362010-07-02 17:12:48 -0700373 * @param uri the HTTP URI to download.
374 */
375 public Request(Uri uri) {
376 if (uri == null) {
377 throw new NullPointerException();
378 }
379 String scheme = uri.getScheme();
Paul Westbrook86a60192010-09-15 12:55:49 -0700380 if (scheme == null || (!scheme.equals("http") && !scheme.equals("https"))) {
381 throw new IllegalArgumentException("Can only download HTTP/HTTPS URIs: " + uri);
Steve Howarda2709362010-07-02 17:12:48 -0700382 }
383 mUri = uri;
384 }
385
386 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700387 * Set the local destination for the downloaded file. Must be a file URI to a path on
Steve Howarda2709362010-07-02 17:12:48 -0700388 * external storage, and the calling application must have the WRITE_EXTERNAL_STORAGE
389 * permission.
Vasu Nori5be894e2010-11-02 21:55:30 -0700390 * <p>
391 * The downloaded file is not scanned by MediaScanner.
392 * But it can be made scannable by calling {@link #allowScanningByMediaScanner()}.
393 * <p>
Steve Howard4f564cd2010-09-22 15:57:25 -0700394 * By default, downloads are saved to a generated filename in the shared download cache and
395 * may be deleted by the system at any time to reclaim space.
Steve Howarda2709362010-07-02 17:12:48 -0700396 *
397 * @return this object
398 */
399 public Request setDestinationUri(Uri uri) {
400 mDestinationUri = uri;
401 return this;
402 }
403
404 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700405 * Set the local destination for the downloaded file to a path within the application's
406 * external files directory (as returned by {@link Context#getExternalFilesDir(String)}.
Vasu Nori5be894e2010-11-02 21:55:30 -0700407 * <p>
408 * The downloaded file is not scanned by MediaScanner.
409 * But it can be made scannable by calling {@link #allowScanningByMediaScanner()}.
Steve Howard4f564cd2010-09-22 15:57:25 -0700410 *
411 * @param context the {@link Context} to use in determining the external files directory
412 * @param dirType the directory type to pass to {@link Context#getExternalFilesDir(String)}
413 * @param subPath the path within the external directory, including the destination filename
414 * @return this object
415 */
416 public Request setDestinationInExternalFilesDir(Context context, String dirType,
417 String subPath) {
418 setDestinationFromBase(context.getExternalFilesDir(dirType), subPath);
419 return this;
420 }
421
422 /**
423 * Set the local destination for the downloaded file to a path within the public external
424 * storage directory (as returned by
425 * {@link Environment#getExternalStoragePublicDirectory(String)}.
Vasu Nori5be894e2010-11-02 21:55:30 -0700426 *<p>
427 * The downloaded file is not scanned by MediaScanner.
428 * But it can be made scannable by calling {@link #allowScanningByMediaScanner()}.
Steve Howard4f564cd2010-09-22 15:57:25 -0700429 *
430 * @param dirType the directory type to pass to
431 * {@link Environment#getExternalStoragePublicDirectory(String)}
432 * @param subPath the path within the external directory, including the destination filename
433 * @return this object
434 */
435 public Request setDestinationInExternalPublicDir(String dirType, String subPath) {
436 setDestinationFromBase(Environment.getExternalStoragePublicDirectory(dirType), subPath);
437 return this;
438 }
439
440 private void setDestinationFromBase(File base, String subPath) {
441 if (subPath == null) {
442 throw new NullPointerException("subPath cannot be null");
443 }
444 mDestinationUri = Uri.withAppendedPath(Uri.fromFile(base), subPath);
445 }
446
447 /**
Vasu Nori5be894e2010-11-02 21:55:30 -0700448 * If the file to be downloaded is to be scanned by MediaScanner, this method
449 * should be called before {@link DownloadManager#enqueue(Request)} is called.
450 */
451 public void allowScanningByMediaScanner() {
452 mScannable = true;
453 }
454
455 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700456 * Add an HTTP header to be included with the download request. The header will be added to
457 * the end of the list.
Steve Howarda2709362010-07-02 17:12:48 -0700458 * @param header HTTP header name
459 * @param value header value
460 * @return this object
Steve Howard4f564cd2010-09-22 15:57:25 -0700461 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2">HTTP/1.1
462 * Message Headers</a>
Steve Howarda2709362010-07-02 17:12:48 -0700463 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700464 public Request addRequestHeader(String header, String value) {
465 if (header == null) {
466 throw new NullPointerException("header cannot be null");
467 }
468 if (header.contains(":")) {
469 throw new IllegalArgumentException("header may not contain ':'");
470 }
471 if (value == null) {
472 value = "";
473 }
474 mRequestHeaders.add(Pair.create(header, value));
Steve Howarda2709362010-07-02 17:12:48 -0700475 return this;
476 }
477
478 /**
Steve Howard610c4352010-09-30 18:30:04 -0700479 * Set the title of this download, to be displayed in notifications (if enabled). If no
480 * title is given, a default one will be assigned based on the download filename, once the
481 * download starts.
Steve Howarda2709362010-07-02 17:12:48 -0700482 * @return this object
483 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700484 public Request setTitle(CharSequence title) {
Steve Howarda2709362010-07-02 17:12:48 -0700485 mTitle = title;
486 return this;
487 }
488
489 /**
490 * Set a description of this download, to be displayed in notifications (if enabled)
491 * @return this object
492 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700493 public Request setDescription(CharSequence description) {
Steve Howarda2709362010-07-02 17:12:48 -0700494 mDescription = description;
495 return this;
496 }
497
498 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700499 * Set the MIME content type of this download. This will override the content type declared
Steve Howarda2709362010-07-02 17:12:48 -0700500 * in the server's response.
Steve Howard4f564cd2010-09-22 15:57:25 -0700501 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7">HTTP/1.1
502 * Media Types</a>
Steve Howarda2709362010-07-02 17:12:48 -0700503 * @return this object
504 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700505 public Request setMimeType(String mimeType) {
506 mMimeType = mimeType;
Steve Howarda2709362010-07-02 17:12:48 -0700507 return this;
508 }
509
510 /**
Steve Howard8e15afe2010-07-28 17:12:40 -0700511 * Control whether a system notification is posted by the download manager while this
512 * download is running. If enabled, the download manager posts notifications about downloads
513 * through the system {@link android.app.NotificationManager}. By default, a notification is
514 * shown.
Steve Howarda2709362010-07-02 17:12:48 -0700515 *
Steve Howard8e15afe2010-07-28 17:12:40 -0700516 * If set to false, this requires the permission
517 * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
518 *
519 * @param show whether the download manager should show a notification for this download.
Steve Howarda2709362010-07-02 17:12:48 -0700520 * @return this object
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700521 * @deprecated use {@link #setNotificationVisibility(int)}
Steve Howarda2709362010-07-02 17:12:48 -0700522 */
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700523 @Deprecated
Steve Howard8e15afe2010-07-28 17:12:40 -0700524 public Request setShowRunningNotification(boolean show) {
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700525 return (show) ? setNotificationVisibility(VISIBILITY_VISIBLE) :
526 setNotificationVisibility(VISIBILITY_HIDDEN);
527 }
528
529 /**
530 * Control whether a system notification is posted by the download manager while this
531 * download is running or when it is completed.
532 * If enabled, the download manager posts notifications about downloads
533 * through the system {@link android.app.NotificationManager}.
534 * By default, a notification is shown only when the download is in progress.
535 *<p>
536 * It can take the following values: {@link #VISIBILITY_HIDDEN},
537 * {@link #VISIBILITY_VISIBLE},
538 * {@link #VISIBILITY_VISIBLE_NOTIFY_COMPLETED}.
539 *<p>
540 * If set to {@link #VISIBILITY_HIDDEN}, this requires the permission
541 * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
542 *
543 * @param visibility the visibility setting value
544 * @return this object
545 */
546 public Request setNotificationVisibility(int visibility) {
547 mNotificationVisibility = visibility;
Steve Howarda2709362010-07-02 17:12:48 -0700548 return this;
549 }
550
Steve Howardb8e07a52010-07-21 14:53:21 -0700551 /**
552 * Restrict the types of networks over which this download may proceed. By default, all
553 * network types are allowed.
554 * @param flags any combination of the NETWORK_* bit flags.
555 * @return this object
556 */
Steve Howarda2709362010-07-02 17:12:48 -0700557 public Request setAllowedNetworkTypes(int flags) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700558 mAllowedNetworkTypes = flags;
559 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700560 }
561
Steve Howardb8e07a52010-07-21 14:53:21 -0700562 /**
563 * Set whether this download may proceed over a roaming connection. By default, roaming is
564 * allowed.
565 * @param allowed whether to allow a roaming connection to be used
566 * @return this object
567 */
Steve Howarda2709362010-07-02 17:12:48 -0700568 public Request setAllowedOverRoaming(boolean allowed) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700569 mRoamingAllowed = allowed;
570 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700571 }
572
573 /**
Steve Howard90fb15a2010-09-09 16:13:41 -0700574 * Set whether this download should be displayed in the system's Downloads UI. True by
575 * default.
576 * @param isVisible whether to display this download in the Downloads UI
577 * @return this object
578 */
579 public Request setVisibleInDownloadsUi(boolean isVisible) {
580 mIsVisibleInDownloadsUi = isVisible;
581 return this;
582 }
583
584 /**
Steve Howarda2709362010-07-02 17:12:48 -0700585 * @return ContentValues to be passed to DownloadProvider.insert()
586 */
Steve Howardb8e07a52010-07-21 14:53:21 -0700587 ContentValues toContentValues(String packageName) {
Steve Howarda2709362010-07-02 17:12:48 -0700588 ContentValues values = new ContentValues();
589 assert mUri != null;
Vasu Norief7e33b2010-10-20 13:26:02 -0700590 values.put(Downloads.Impl.COLUMN_URI, mUri.toString());
Steve Howardb8e07a52010-07-21 14:53:21 -0700591 values.put(Downloads.Impl.COLUMN_IS_PUBLIC_API, true);
Vasu Norief7e33b2010-10-20 13:26:02 -0700592 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE, packageName);
Steve Howarda2709362010-07-02 17:12:48 -0700593
594 if (mDestinationUri != null) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700595 values.put(Downloads.Impl.COLUMN_DESTINATION, Downloads.Impl.DESTINATION_FILE_URI);
596 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, mDestinationUri.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700597 } else {
Vasu Norief7e33b2010-10-20 13:26:02 -0700598 values.put(Downloads.Impl.COLUMN_DESTINATION,
599 Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE);
Steve Howarda2709362010-07-02 17:12:48 -0700600 }
Vasu Nori5be894e2010-11-02 21:55:30 -0700601 // is the file supposed to be media-scannable?
Vasu Nori1cde3fb2010-11-05 11:02:52 -0700602 values.put(Downloads.Impl.COLUMN_MEDIA_SCANNED, (mScannable) ? SCANNABLE_VALUE_YES :
603 SCANNABLE_VALUE_NO);
Steve Howarda2709362010-07-02 17:12:48 -0700604
605 if (!mRequestHeaders.isEmpty()) {
Steve Howardea9147d2010-07-13 19:02:45 -0700606 encodeHttpHeaders(values);
Steve Howarda2709362010-07-02 17:12:48 -0700607 }
608
Vasu Norief7e33b2010-10-20 13:26:02 -0700609 putIfNonNull(values, Downloads.Impl.COLUMN_TITLE, mTitle);
610 putIfNonNull(values, Downloads.Impl.COLUMN_DESCRIPTION, mDescription);
611 putIfNonNull(values, Downloads.Impl.COLUMN_MIME_TYPE, mMimeType);
Steve Howarda2709362010-07-02 17:12:48 -0700612
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700613 values.put(Downloads.Impl.COLUMN_VISIBILITY, mNotificationVisibility);
Steve Howardb8e07a52010-07-21 14:53:21 -0700614 values.put(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES, mAllowedNetworkTypes);
615 values.put(Downloads.Impl.COLUMN_ALLOW_ROAMING, mRoamingAllowed);
Steve Howard90fb15a2010-09-09 16:13:41 -0700616 values.put(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, mIsVisibleInDownloadsUi);
Steve Howardb8e07a52010-07-21 14:53:21 -0700617
Steve Howarda2709362010-07-02 17:12:48 -0700618 return values;
619 }
620
Steve Howardea9147d2010-07-13 19:02:45 -0700621 private void encodeHttpHeaders(ContentValues values) {
622 int index = 0;
Steve Howard4f564cd2010-09-22 15:57:25 -0700623 for (Pair<String, String> header : mRequestHeaders) {
624 String headerString = header.first + ": " + header.second;
Steve Howardea9147d2010-07-13 19:02:45 -0700625 values.put(Downloads.Impl.RequestHeaders.INSERT_KEY_PREFIX + index, headerString);
626 index++;
627 }
628 }
629
Steve Howard4f564cd2010-09-22 15:57:25 -0700630 private void putIfNonNull(ContentValues contentValues, String key, Object value) {
Steve Howarda2709362010-07-02 17:12:48 -0700631 if (value != null) {
Steve Howard4f564cd2010-09-22 15:57:25 -0700632 contentValues.put(key, value.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700633 }
634 }
635 }
636
637 /**
638 * This class may be used to filter download manager queries.
639 */
640 public static class Query {
Steve Howardf054e192010-09-01 18:26:26 -0700641 /**
642 * Constant for use with {@link #orderBy}
643 * @hide
644 */
645 public static final int ORDER_ASCENDING = 1;
646
647 /**
648 * Constant for use with {@link #orderBy}
649 * @hide
650 */
651 public static final int ORDER_DESCENDING = 2;
652
Steve Howard64c48b82010-10-07 17:53:52 -0700653 private long[] mIds = null;
Steve Howarda2709362010-07-02 17:12:48 -0700654 private Integer mStatusFlags = null;
Vasu Norief7e33b2010-10-20 13:26:02 -0700655 private String mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
Steve Howardf054e192010-09-01 18:26:26 -0700656 private int mOrderDirection = ORDER_DESCENDING;
Steve Howard90fb15a2010-09-09 16:13:41 -0700657 private boolean mOnlyIncludeVisibleInDownloadsUi = false;
Steve Howarda2709362010-07-02 17:12:48 -0700658
659 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700660 * Include only the downloads with the given IDs.
Steve Howarda2709362010-07-02 17:12:48 -0700661 * @return this object
662 */
Steve Howard64c48b82010-10-07 17:53:52 -0700663 public Query setFilterById(long... ids) {
664 mIds = ids;
Steve Howarda2709362010-07-02 17:12:48 -0700665 return this;
666 }
667
668 /**
669 * Include only downloads with status matching any the given status flags.
670 * @param flags any combination of the STATUS_* bit flags
671 * @return this object
672 */
673 public Query setFilterByStatus(int flags) {
674 mStatusFlags = flags;
675 return this;
676 }
677
678 /**
Steve Howard90fb15a2010-09-09 16:13:41 -0700679 * Controls whether this query includes downloads not visible in the system's Downloads UI.
680 * @param value if true, this query will only include downloads that should be displayed in
681 * the system's Downloads UI; if false (the default), this query will include
682 * both visible and invisible downloads.
683 * @return this object
684 * @hide
685 */
686 public Query setOnlyIncludeVisibleInDownloadsUi(boolean value) {
687 mOnlyIncludeVisibleInDownloadsUi = value;
688 return this;
689 }
690
691 /**
Steve Howardf054e192010-09-01 18:26:26 -0700692 * Change the sort order of the returned Cursor.
693 *
694 * @param column one of the COLUMN_* constants; currently, only
695 * {@link #COLUMN_LAST_MODIFIED_TIMESTAMP} and {@link #COLUMN_TOTAL_SIZE_BYTES} are
696 * supported.
697 * @param direction either {@link #ORDER_ASCENDING} or {@link #ORDER_DESCENDING}
698 * @return this object
699 * @hide
700 */
701 public Query orderBy(String column, int direction) {
702 if (direction != ORDER_ASCENDING && direction != ORDER_DESCENDING) {
703 throw new IllegalArgumentException("Invalid direction: " + direction);
704 }
705
706 if (column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP)) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700707 mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
Steve Howardf054e192010-09-01 18:26:26 -0700708 } else if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700709 mOrderByColumn = Downloads.Impl.COLUMN_TOTAL_BYTES;
Steve Howardf054e192010-09-01 18:26:26 -0700710 } else {
711 throw new IllegalArgumentException("Cannot order by " + column);
712 }
713 mOrderDirection = direction;
714 return this;
715 }
716
717 /**
Steve Howarda2709362010-07-02 17:12:48 -0700718 * Run this query using the given ContentResolver.
719 * @param projection the projection to pass to ContentResolver.query()
720 * @return the Cursor returned by ContentResolver.query()
721 */
Steve Howardeca77fc2010-09-12 18:49:08 -0700722 Cursor runQuery(ContentResolver resolver, String[] projection, Uri baseUri) {
723 Uri uri = baseUri;
Steve Howard90fb15a2010-09-09 16:13:41 -0700724 List<String> selectionParts = new ArrayList<String>();
Steve Howard64c48b82010-10-07 17:53:52 -0700725 String[] selectionArgs = null;
Steve Howarda2709362010-07-02 17:12:48 -0700726
Steve Howard64c48b82010-10-07 17:53:52 -0700727 if (mIds != null) {
728 selectionParts.add(getWhereClauseForIds(mIds));
729 selectionArgs = getWhereArgsForIds(mIds);
Steve Howarda2709362010-07-02 17:12:48 -0700730 }
731
732 if (mStatusFlags != null) {
733 List<String> parts = new ArrayList<String>();
734 if ((mStatusFlags & STATUS_PENDING) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700735 parts.add(statusClause("=", Downloads.Impl.STATUS_PENDING));
Steve Howarda2709362010-07-02 17:12:48 -0700736 }
737 if ((mStatusFlags & STATUS_RUNNING) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700738 parts.add(statusClause("=", Downloads.Impl.STATUS_RUNNING));
Steve Howarda2709362010-07-02 17:12:48 -0700739 }
740 if ((mStatusFlags & STATUS_PAUSED) != 0) {
Steve Howard3e8c1d32010-09-29 17:03:32 -0700741 parts.add(statusClause("=", Downloads.Impl.STATUS_PAUSED_BY_APP));
742 parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_TO_RETRY));
743 parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_FOR_NETWORK));
744 parts.add(statusClause("=", Downloads.Impl.STATUS_QUEUED_FOR_WIFI));
Steve Howarda2709362010-07-02 17:12:48 -0700745 }
746 if ((mStatusFlags & STATUS_SUCCESSFUL) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700747 parts.add(statusClause("=", Downloads.Impl.STATUS_SUCCESS));
Steve Howarda2709362010-07-02 17:12:48 -0700748 }
749 if ((mStatusFlags & STATUS_FAILED) != 0) {
750 parts.add("(" + statusClause(">=", 400)
751 + " AND " + statusClause("<", 600) + ")");
752 }
Steve Howard90fb15a2010-09-09 16:13:41 -0700753 selectionParts.add(joinStrings(" OR ", parts));
Steve Howarda2709362010-07-02 17:12:48 -0700754 }
Steve Howardf054e192010-09-01 18:26:26 -0700755
Steve Howard90fb15a2010-09-09 16:13:41 -0700756 if (mOnlyIncludeVisibleInDownloadsUi) {
757 selectionParts.add(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI + " != '0'");
758 }
759
Vasu Nori216fa222010-10-12 23:08:13 -0700760 // only return rows which are not marked 'deleted = 1'
761 selectionParts.add(Downloads.Impl.COLUMN_DELETED + " != '1'");
762
Steve Howard90fb15a2010-09-09 16:13:41 -0700763 String selection = joinStrings(" AND ", selectionParts);
Steve Howardf054e192010-09-01 18:26:26 -0700764 String orderDirection = (mOrderDirection == ORDER_ASCENDING ? "ASC" : "DESC");
765 String orderBy = mOrderByColumn + " " + orderDirection;
766
Steve Howard64c48b82010-10-07 17:53:52 -0700767 return resolver.query(uri, projection, selection, selectionArgs, orderBy);
Steve Howarda2709362010-07-02 17:12:48 -0700768 }
769
770 private String joinStrings(String joiner, Iterable<String> parts) {
771 StringBuilder builder = new StringBuilder();
772 boolean first = true;
773 for (String part : parts) {
774 if (!first) {
775 builder.append(joiner);
776 }
777 builder.append(part);
778 first = false;
779 }
780 return builder.toString();
781 }
782
783 private String statusClause(String operator, int value) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700784 return Downloads.Impl.COLUMN_STATUS + operator + "'" + value + "'";
Steve Howarda2709362010-07-02 17:12:48 -0700785 }
786 }
787
788 private ContentResolver mResolver;
Steve Howardb8e07a52010-07-21 14:53:21 -0700789 private String mPackageName;
Steve Howardeca77fc2010-09-12 18:49:08 -0700790 private Uri mBaseUri = Downloads.Impl.CONTENT_URI;
Steve Howarda2709362010-07-02 17:12:48 -0700791
792 /**
793 * @hide
794 */
Steve Howardb8e07a52010-07-21 14:53:21 -0700795 public DownloadManager(ContentResolver resolver, String packageName) {
Steve Howarda2709362010-07-02 17:12:48 -0700796 mResolver = resolver;
Steve Howardb8e07a52010-07-21 14:53:21 -0700797 mPackageName = packageName;
Steve Howarda2709362010-07-02 17:12:48 -0700798 }
799
800 /**
Steve Howardeca77fc2010-09-12 18:49:08 -0700801 * Makes this object access the download provider through /all_downloads URIs rather than
802 * /my_downloads URIs, for clients that have permission to do so.
803 * @hide
804 */
805 public void setAccessAllDownloads(boolean accessAllDownloads) {
806 if (accessAllDownloads) {
807 mBaseUri = Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI;
808 } else {
809 mBaseUri = Downloads.Impl.CONTENT_URI;
810 }
811 }
812
813 /**
Steve Howarda2709362010-07-02 17:12:48 -0700814 * Enqueue a new download. The download will start automatically once the download manager is
815 * ready to execute it and connectivity is available.
816 *
817 * @param request the parameters specifying this download
818 * @return an ID for the download, unique across the system. This ID is used to make future
819 * calls related to this download.
820 */
821 public long enqueue(Request request) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700822 ContentValues values = request.toContentValues(mPackageName);
Vasu Norief7e33b2010-10-20 13:26:02 -0700823 Uri downloadUri = mResolver.insert(Downloads.Impl.CONTENT_URI, values);
Steve Howarda2709362010-07-02 17:12:48 -0700824 long id = Long.parseLong(downloadUri.getLastPathSegment());
825 return id;
826 }
827
828 /**
Vasu Nori216fa222010-10-12 23:08:13 -0700829 * Marks the specified download as 'to be deleted'. This is done when a completed download
830 * is to be removed but the row was stored without enough info to delete the corresponding
831 * metadata from Mediaprovider database. Actual cleanup of this row is done in DownloadService.
832 *
833 * @param ids the IDs of the downloads to be marked 'deleted'
834 * @return the number of downloads actually updated
835 * @hide
836 */
837 public int markRowDeleted(long... ids) {
838 if (ids == null || ids.length == 0) {
839 // called with nothing to remove!
840 throw new IllegalArgumentException("input param 'ids' can't be null");
841 }
842 ContentValues values = new ContentValues();
843 values.put(Downloads.Impl.COLUMN_DELETED, 1);
844 return mResolver.update(mBaseUri, values, getWhereClauseForIds(ids),
845 getWhereArgsForIds(ids));
846 }
847
848 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700849 * Cancel downloads and remove them from the download manager. Each download will be stopped if
Steve Howarda2709362010-07-02 17:12:48 -0700850 * it was running, and it will no longer be accessible through the download manager. If a file
Steve Howard64c48b82010-10-07 17:53:52 -0700851 * was already downloaded to external storage, it will not be deleted.
Steve Howarda2709362010-07-02 17:12:48 -0700852 *
Steve Howard64c48b82010-10-07 17:53:52 -0700853 * @param ids the IDs of the downloads to remove
854 * @return the number of downloads actually removed
Steve Howarda2709362010-07-02 17:12:48 -0700855 */
Steve Howard64c48b82010-10-07 17:53:52 -0700856 public int remove(long... ids) {
Vasu Norie16c43b2010-11-06 18:48:08 -0700857 return markRowDeleted(ids);
Steve Howarda2709362010-07-02 17:12:48 -0700858 }
859
860 /**
861 * Query the download manager about downloads that have been requested.
862 * @param query parameters specifying filters for this query
863 * @return a Cursor over the result set of downloads, with columns consisting of all the
864 * COLUMN_* constants.
865 */
866 public Cursor query(Query query) {
Steve Howardeca77fc2010-09-12 18:49:08 -0700867 Cursor underlyingCursor = query.runQuery(mResolver, UNDERLYING_COLUMNS, mBaseUri);
Steve Howardf054e192010-09-01 18:26:26 -0700868 if (underlyingCursor == null) {
869 return null;
870 }
Steve Howardeca77fc2010-09-12 18:49:08 -0700871 return new CursorTranslator(underlyingCursor, mBaseUri);
Steve Howarda2709362010-07-02 17:12:48 -0700872 }
873
874 /**
875 * Open a downloaded file for reading. The download must have completed.
876 * @param id the ID of the download
877 * @return a read-only {@link ParcelFileDescriptor}
878 * @throws FileNotFoundException if the destination file does not already exist
879 */
880 public ParcelFileDescriptor openDownloadedFile(long id) throws FileNotFoundException {
881 return mResolver.openFileDescriptor(getDownloadUri(id), "r");
882 }
883
884 /**
Vasu Nori5be894e2010-11-02 21:55:30 -0700885 * Returns {@link Uri} for the given downloaded file id, if the file is
886 * downloaded successfully. otherwise, null is returned.
887 *<p>
888 * If the specified downloaded file is in external storage (for example, /sdcard dir),
Vasu Nori6e2b2a62010-11-16 17:58:22 -0800889 * then it is assumed to be safe for anyone to read and the returned {@link Uri} corresponds
890 * to the filepath on sdcard.
Vasu Nori5be894e2010-11-02 21:55:30 -0700891 *
892 * @param id the id of the downloaded file.
Vasu Nori1cde3fb2010-11-05 11:02:52 -0700893 * @return the {@link Uri} for the given downloaded file id, if download was successful. null
Vasu Nori5be894e2010-11-02 21:55:30 -0700894 * otherwise.
895 */
896 public Uri getUriForDownloadedFile(long id) {
897 // to check if the file is in cache, get its destination from the database
898 Query query = new Query().setFilterById(id);
899 Cursor cursor = null;
900 try {
901 cursor = query(query);
902 if (cursor == null) {
903 return null;
904 }
905 while (cursor.moveToFirst()) {
Vasu Nori6e2b2a62010-11-16 17:58:22 -0800906 int status = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_STATUS));
Vasu Nori5be894e2010-11-02 21:55:30 -0700907 if (DownloadManager.STATUS_SUCCESSFUL == status) {
908 int indx = cursor.getColumnIndexOrThrow(
909 Downloads.Impl.COLUMN_DESTINATION);
910 int destination = cursor.getInt(indx);
911 // TODO: if we ever add API to DownloadManager to let the caller specify
Vasu Nori1cde3fb2010-11-05 11:02:52 -0700912 // non-external storage for a downloaded file, then the following code
Vasu Nori5be894e2010-11-02 21:55:30 -0700913 // should also check for that destination.
914 if (destination == Downloads.Impl.DESTINATION_CACHE_PARTITION ||
915 destination == Downloads.Impl.DESTINATION_CACHE_PARTITION_NOROAMING ||
916 destination == Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE) {
917 // return private uri
918 return ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI, id);
919 } else {
920 // return public uri
Vasu Nori6e2b2a62010-11-16 17:58:22 -0800921 String path = cursor.getString(
922 cursor.getColumnIndexOrThrow(COLUMN_LOCAL_FILENAME));
923 return Uri.fromFile(new File(path));
Vasu Nori5be894e2010-11-02 21:55:30 -0700924 }
925 }
926 }
927 } finally {
928 if (cursor != null) {
929 cursor.close();
930 }
931 }
932 // downloaded file not found or its status is not 'successfully completed'
933 return null;
934 }
935
936 /**
Vasu Nori6e2b2a62010-11-16 17:58:22 -0800937 * Returns {@link Uri} for the given downloaded file id, if the file is
938 * downloaded successfully. otherwise, null is returned.
939 *<p>
940 * If the specified downloaded file is in external storage (for example, /sdcard dir),
941 * then it is assumed to be safe for anyone to read and the returned {@link Uri} corresponds
942 * to the filepath on sdcard.
943 *
944 * @param id the id of the downloaded file.
945 * @return the {@link Uri} for the given downloaded file id, if download was successful. null
946 * otherwise.
947 */
948 public String getMimeTypeForDownloadedFile(long id) {
949 Query query = new Query().setFilterById(id);
950 Cursor cursor = null;
951 try {
952 cursor = query(query);
953 if (cursor == null) {
954 return null;
955 }
956 while (cursor.moveToFirst()) {
957 return cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_MEDIA_TYPE));
958 }
959 } finally {
960 if (cursor != null) {
961 cursor.close();
962 }
963 }
964 // downloaded file not found or its status is not 'successfully completed'
965 return null;
966 }
967
968 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700969 * Restart the given downloads, which must have already completed (successfully or not). This
Steve Howard90fb15a2010-09-09 16:13:41 -0700970 * method will only work when called from within the download manager's process.
Steve Howard64c48b82010-10-07 17:53:52 -0700971 * @param ids the IDs of the downloads
Steve Howard90fb15a2010-09-09 16:13:41 -0700972 * @hide
973 */
Steve Howard64c48b82010-10-07 17:53:52 -0700974 public void restartDownload(long... ids) {
975 Cursor cursor = query(new Query().setFilterById(ids));
Steve Howard90fb15a2010-09-09 16:13:41 -0700976 try {
Steve Howard64c48b82010-10-07 17:53:52 -0700977 for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
978 int status = cursor.getInt(cursor.getColumnIndex(COLUMN_STATUS));
979 if (status != STATUS_SUCCESSFUL && status != STATUS_FAILED) {
980 throw new IllegalArgumentException("Cannot restart incomplete download: "
981 + cursor.getLong(cursor.getColumnIndex(COLUMN_ID)));
982 }
Steve Howard90fb15a2010-09-09 16:13:41 -0700983 }
984 } finally {
985 cursor.close();
986 }
987
988 ContentValues values = new ContentValues();
989 values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, 0);
990 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, -1);
991 values.putNull(Downloads.Impl._DATA);
992 values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING);
Steve Howard64c48b82010-10-07 17:53:52 -0700993 mResolver.update(mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
Steve Howard90fb15a2010-09-09 16:13:41 -0700994 }
995
996 /**
Steve Howarda2709362010-07-02 17:12:48 -0700997 * Get the DownloadProvider URI for the download with the given ID.
998 */
Steve Howardeca77fc2010-09-12 18:49:08 -0700999 Uri getDownloadUri(long id) {
1000 return ContentUris.withAppendedId(mBaseUri, id);
Steve Howarda2709362010-07-02 17:12:48 -07001001 }
1002
1003 /**
Steve Howard64c48b82010-10-07 17:53:52 -07001004 * Get a parameterized SQL WHERE clause to select a bunch of IDs.
1005 */
1006 static String getWhereClauseForIds(long[] ids) {
1007 StringBuilder whereClause = new StringBuilder();
Vasu Norie7be6bd2010-10-10 14:58:08 -07001008 whereClause.append("(");
Steve Howard64c48b82010-10-07 17:53:52 -07001009 for (int i = 0; i < ids.length; i++) {
1010 if (i > 0) {
Vasu Norie7be6bd2010-10-10 14:58:08 -07001011 whereClause.append("OR ");
Steve Howard64c48b82010-10-07 17:53:52 -07001012 }
Vasu Norie7be6bd2010-10-10 14:58:08 -07001013 whereClause.append(Downloads.Impl._ID);
1014 whereClause.append(" = ? ");
Steve Howard64c48b82010-10-07 17:53:52 -07001015 }
1016 whereClause.append(")");
1017 return whereClause.toString();
1018 }
1019
1020 /**
1021 * Get the selection args for a clause returned by {@link #getWhereClauseForIds(long[])}.
1022 */
1023 static String[] getWhereArgsForIds(long[] ids) {
1024 String[] whereArgs = new String[ids.length];
1025 for (int i = 0; i < ids.length; i++) {
1026 whereArgs[i] = Long.toString(ids[i]);
1027 }
1028 return whereArgs;
1029 }
1030
1031 /**
Steve Howarda2709362010-07-02 17:12:48 -07001032 * This class wraps a cursor returned by DownloadProvider -- the "underlying cursor" -- and
1033 * presents a different set of columns, those defined in the DownloadManager.COLUMN_* constants.
1034 * Some columns correspond directly to underlying values while others are computed from
1035 * underlying data.
1036 */
1037 private static class CursorTranslator extends CursorWrapper {
Steve Howardeca77fc2010-09-12 18:49:08 -07001038 private Uri mBaseUri;
1039
1040 public CursorTranslator(Cursor cursor, Uri baseUri) {
Steve Howarda2709362010-07-02 17:12:48 -07001041 super(cursor);
Steve Howardeca77fc2010-09-12 18:49:08 -07001042 mBaseUri = baseUri;
Steve Howarda2709362010-07-02 17:12:48 -07001043 }
1044
1045 @Override
Steve Howarda2709362010-07-02 17:12:48 -07001046 public int getInt(int columnIndex) {
1047 return (int) getLong(columnIndex);
1048 }
1049
1050 @Override
1051 public long getLong(int columnIndex) {
Vasu Norie16c43b2010-11-06 18:48:08 -07001052 if (getColumnName(columnIndex).equals(COLUMN_REASON)) {
1053 return getReason(super.getInt(getColumnIndex(Downloads.Impl.COLUMN_STATUS)));
1054 } else if (getColumnName(columnIndex).equals(COLUMN_STATUS)) {
1055 return translateStatus(super.getInt(getColumnIndex(Downloads.Impl.COLUMN_STATUS)));
1056 } else {
1057 return super.getLong(columnIndex);
1058 }
Steve Howarda2709362010-07-02 17:12:48 -07001059 }
1060
1061 @Override
1062 public String getString(int columnIndex) {
Vasu Norie16c43b2010-11-06 18:48:08 -07001063 return (getColumnName(columnIndex).equals(COLUMN_LOCAL_URI)) ? getLocalUri() :
1064 super.getString(columnIndex);
Steve Howardeca77fc2010-09-12 18:49:08 -07001065 }
1066
1067 private String getLocalUri() {
Vasu Norie16c43b2010-11-06 18:48:08 -07001068 long destinationType = getLong(getColumnIndex(Downloads.Impl.COLUMN_DESTINATION));
1069 if (destinationType == Downloads.Impl.DESTINATION_FILE_URI ||
1070 destinationType == Downloads.Impl.DESTINATION_EXTERNAL) {
Vasu Nori98f03072010-11-15 17:22:20 -08001071 String localPath = getString(getColumnIndex(COLUMN_LOCAL_FILENAME));
Steve Howard99047d72010-09-29 17:41:37 -07001072 if (localPath == null) {
1073 return null;
1074 }
1075 return Uri.fromFile(new File(localPath)).toString();
Steve Howardbb0d23b2010-09-22 18:56:29 -07001076 }
1077
Steve Howardeca77fc2010-09-12 18:49:08 -07001078 // return content URI for cache download
Vasu Norie16c43b2010-11-06 18:48:08 -07001079 long downloadId = getLong(getColumnIndex(Downloads.Impl._ID));
Steve Howardeca77fc2010-09-12 18:49:08 -07001080 return ContentUris.withAppendedId(mBaseUri, downloadId).toString();
Steve Howarda2709362010-07-02 17:12:48 -07001081 }
1082
Steve Howard3e8c1d32010-09-29 17:03:32 -07001083 private long getReason(int status) {
1084 switch (translateStatus(status)) {
1085 case STATUS_FAILED:
1086 return getErrorCode(status);
1087
1088 case STATUS_PAUSED:
1089 return getPausedReason(status);
1090
1091 default:
1092 return 0; // arbitrary value when status is not an error
Steve Howarda2709362010-07-02 17:12:48 -07001093 }
Steve Howard3e8c1d32010-09-29 17:03:32 -07001094 }
1095
1096 private long getPausedReason(int status) {
1097 switch (status) {
1098 case Downloads.Impl.STATUS_WAITING_TO_RETRY:
1099 return PAUSED_WAITING_TO_RETRY;
1100
1101 case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
1102 return PAUSED_WAITING_FOR_NETWORK;
1103
1104 case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
1105 return PAUSED_QUEUED_FOR_WIFI;
1106
1107 default:
1108 return PAUSED_UNKNOWN;
1109 }
1110 }
1111
1112 private long getErrorCode(int status) {
Steve Howard33bbd122010-08-02 17:51:29 -07001113 if ((400 <= status && status < Downloads.Impl.MIN_ARTIFICIAL_ERROR_STATUS)
1114 || (500 <= status && status < 600)) {
Steve Howarda2709362010-07-02 17:12:48 -07001115 // HTTP status code
1116 return status;
1117 }
1118
1119 switch (status) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001120 case Downloads.Impl.STATUS_FILE_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001121 return ERROR_FILE_ERROR;
1122
Vasu Norief7e33b2010-10-20 13:26:02 -07001123 case Downloads.Impl.STATUS_UNHANDLED_HTTP_CODE:
1124 case Downloads.Impl.STATUS_UNHANDLED_REDIRECT:
Steve Howarda2709362010-07-02 17:12:48 -07001125 return ERROR_UNHANDLED_HTTP_CODE;
1126
Vasu Norief7e33b2010-10-20 13:26:02 -07001127 case Downloads.Impl.STATUS_HTTP_DATA_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001128 return ERROR_HTTP_DATA_ERROR;
1129
Vasu Norief7e33b2010-10-20 13:26:02 -07001130 case Downloads.Impl.STATUS_TOO_MANY_REDIRECTS:
Steve Howarda2709362010-07-02 17:12:48 -07001131 return ERROR_TOO_MANY_REDIRECTS;
1132
Vasu Norief7e33b2010-10-20 13:26:02 -07001133 case Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001134 return ERROR_INSUFFICIENT_SPACE;
1135
Vasu Norief7e33b2010-10-20 13:26:02 -07001136 case Downloads.Impl.STATUS_DEVICE_NOT_FOUND_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001137 return ERROR_DEVICE_NOT_FOUND;
1138
Steve Howard33bbd122010-08-02 17:51:29 -07001139 case Downloads.Impl.STATUS_CANNOT_RESUME:
1140 return ERROR_CANNOT_RESUME;
1141
Steve Howarda9e87c92010-09-16 12:02:03 -07001142 case Downloads.Impl.STATUS_FILE_ALREADY_EXISTS_ERROR:
1143 return ERROR_FILE_ALREADY_EXISTS;
1144
Steve Howarda2709362010-07-02 17:12:48 -07001145 default:
1146 return ERROR_UNKNOWN;
1147 }
1148 }
1149
Steve Howard3e8c1d32010-09-29 17:03:32 -07001150 private int translateStatus(int status) {
Steve Howarda2709362010-07-02 17:12:48 -07001151 switch (status) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001152 case Downloads.Impl.STATUS_PENDING:
Steve Howarda2709362010-07-02 17:12:48 -07001153 return STATUS_PENDING;
1154
Vasu Norief7e33b2010-10-20 13:26:02 -07001155 case Downloads.Impl.STATUS_RUNNING:
Steve Howarda2709362010-07-02 17:12:48 -07001156 return STATUS_RUNNING;
1157
Steve Howard3e8c1d32010-09-29 17:03:32 -07001158 case Downloads.Impl.STATUS_PAUSED_BY_APP:
1159 case Downloads.Impl.STATUS_WAITING_TO_RETRY:
1160 case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
1161 case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
Steve Howarda2709362010-07-02 17:12:48 -07001162 return STATUS_PAUSED;
1163
Vasu Norief7e33b2010-10-20 13:26:02 -07001164 case Downloads.Impl.STATUS_SUCCESS:
Steve Howarda2709362010-07-02 17:12:48 -07001165 return STATUS_SUCCESSFUL;
1166
1167 default:
Vasu Norief7e33b2010-10-20 13:26:02 -07001168 assert Downloads.Impl.isStatusError(status);
Steve Howarda2709362010-07-02 17:12:48 -07001169 return STATUS_FAILED;
1170 }
1171 }
1172 }
1173}