blob: cafe0f9552454b3515627e92a3cae5aeb9aac774 [file] [log] [blame]
Steve Howarda2709362010-07-02 17:12:48 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.net;
18
19import android.content.ContentResolver;
20import android.content.ContentValues;
21import android.database.Cursor;
22import android.database.CursorWrapper;
23import android.os.ParcelFileDescriptor;
24import android.provider.Downloads;
Steve Howarda2709362010-07-02 17:12:48 -070025
Steve Howardadcb6972010-07-12 17:09:25 -070026import java.io.File;
Steve Howarda2709362010-07-02 17:12:48 -070027import java.io.FileNotFoundException;
28import java.util.ArrayList;
29import java.util.Arrays;
30import java.util.HashMap;
31import java.util.HashSet;
32import java.util.List;
33import java.util.Map;
34import java.util.Set;
35
36/**
37 * The download manager is a system service that handles long-running HTTP downloads. Clients may
38 * request that a URI be downloaded to a particular destination file. The download manager will
39 * conduct the download in the background, taking care of HTTP interactions and retrying downloads
40 * after failures or across connectivity changes and system reboots.
41 *
42 * Instances of this class should be obtained through
43 * {@link android.content.Context#getSystemService(String)} by passing
44 * {@link android.content.Context#DOWNLOAD_SERVICE}.
Steve Howarda2709362010-07-02 17:12:48 -070045 */
46public class DownloadManager {
47 /**
48 * An identifier for a particular download, unique across the system. Clients use this ID to
49 * make subsequent calls related to the download.
50 */
51 public final static String COLUMN_ID = "id";
52
53 /**
Steve Howard8651bd52010-08-03 12:35:32 -070054 * The client-supplied title for this download. This will be displayed in system notifications.
55 * Defaults to the empty string.
Steve Howarda2709362010-07-02 17:12:48 -070056 */
57 public final static String COLUMN_TITLE = "title";
58
59 /**
60 * The client-supplied description of this download. This will be displayed in system
Steve Howard8651bd52010-08-03 12:35:32 -070061 * notifications. Defaults to the empty string.
Steve Howarda2709362010-07-02 17:12:48 -070062 */
63 public final static String COLUMN_DESCRIPTION = "description";
64
65 /**
66 * URI to be downloaded.
67 */
68 public final static String COLUMN_URI = "uri";
69
70 /**
Steve Howard8651bd52010-08-03 12:35:32 -070071 * Internet Media Type of the downloaded file. If no value is provided upon creation, this will
72 * initially be null and will be filled in based on the server's response once the download has
73 * started.
Steve Howarda2709362010-07-02 17:12:48 -070074 *
75 * @see <a href="http://www.ietf.org/rfc/rfc1590.txt">RFC 1590, defining Media Types</a>
76 */
77 public final static String COLUMN_MEDIA_TYPE = "media_type";
78
79 /**
Steve Howard8651bd52010-08-03 12:35:32 -070080 * Total size of the download in bytes. This will initially be -1 and will be filled in once
81 * the download starts.
Steve Howarda2709362010-07-02 17:12:48 -070082 */
83 public final static String COLUMN_TOTAL_SIZE_BYTES = "total_size";
84
85 /**
86 * Uri where downloaded file will be stored. If a destination is supplied by client, that URI
Steve Howard8651bd52010-08-03 12:35:32 -070087 * will be used here. Otherwise, the value will initially be null and will be filled in with a
88 * generated URI once the download has started.
Steve Howarda2709362010-07-02 17:12:48 -070089 */
90 public final static String COLUMN_LOCAL_URI = "local_uri";
91
92 /**
93 * Current status of the download, as one of the STATUS_* constants.
94 */
95 public final static String COLUMN_STATUS = "status";
96
97 /**
98 * Indicates the type of error that occurred, when {@link #COLUMN_STATUS} is
99 * {@link #STATUS_FAILED}. If an HTTP error occurred, this will hold the HTTP status code as
100 * defined in RFC 2616. Otherwise, it will hold one of the ERROR_* constants.
101 *
102 * If {@link #COLUMN_STATUS} is not {@link #STATUS_FAILED}, this column's value is undefined.
103 *
104 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1.1">RFC 2616
105 * status codes</a>
106 */
107 public final static String COLUMN_ERROR_CODE = "error_code";
108
109 /**
110 * Number of bytes download so far.
111 */
112 public final static String COLUMN_BYTES_DOWNLOADED_SO_FAR = "bytes_so_far";
113
114 /**
Steve Howardadcb6972010-07-12 17:09:25 -0700115 * Timestamp when the download was last modified, in {@link System#currentTimeMillis
Steve Howarda2709362010-07-02 17:12:48 -0700116 * System.currentTimeMillis()} (wall clock time in UTC).
117 */
Steve Howardadcb6972010-07-12 17:09:25 -0700118 public final static String COLUMN_LAST_MODIFIED_TIMESTAMP = "last_modified_timestamp";
Steve Howarda2709362010-07-02 17:12:48 -0700119
120
121 /**
122 * Value of {@link #COLUMN_STATUS} when the download is waiting to start.
123 */
124 public final static int STATUS_PENDING = 1 << 0;
125
126 /**
127 * Value of {@link #COLUMN_STATUS} when the download is currently running.
128 */
129 public final static int STATUS_RUNNING = 1 << 1;
130
131 /**
132 * Value of {@link #COLUMN_STATUS} when the download is waiting to retry or resume.
133 */
134 public final static int STATUS_PAUSED = 1 << 2;
135
136 /**
137 * Value of {@link #COLUMN_STATUS} when the download has successfully completed.
138 */
139 public final static int STATUS_SUCCESSFUL = 1 << 3;
140
141 /**
142 * Value of {@link #COLUMN_STATUS} when the download has failed (and will not be retried).
143 */
144 public final static int STATUS_FAILED = 1 << 4;
145
146
147 /**
148 * Value of COLUMN_ERROR_CODE when the download has completed with an error that doesn't fit
149 * under any other error code.
150 */
151 public final static int ERROR_UNKNOWN = 1000;
152
153 /**
154 * Value of {@link #COLUMN_ERROR_CODE} when a storage issue arises which doesn't fit under any
155 * other error code. Use the more specific {@link #ERROR_INSUFFICIENT_SPACE} and
156 * {@link #ERROR_DEVICE_NOT_FOUND} when appropriate.
157 */
158 public final static int ERROR_FILE_ERROR = 1001;
159
160 /**
161 * Value of {@link #COLUMN_ERROR_CODE} when an HTTP code was received that download manager
162 * can't handle.
163 */
164 public final static int ERROR_UNHANDLED_HTTP_CODE = 1002;
165
166 /**
167 * Value of {@link #COLUMN_ERROR_CODE} when an error receiving or processing data occurred at
168 * the HTTP level.
169 */
170 public final static int ERROR_HTTP_DATA_ERROR = 1004;
171
172 /**
173 * Value of {@link #COLUMN_ERROR_CODE} when there were too many redirects.
174 */
175 public final static int ERROR_TOO_MANY_REDIRECTS = 1005;
176
177 /**
178 * Value of {@link #COLUMN_ERROR_CODE} when there was insufficient storage space. Typically,
179 * this is because the SD card is full.
180 */
181 public final static int ERROR_INSUFFICIENT_SPACE = 1006;
182
183 /**
184 * Value of {@link #COLUMN_ERROR_CODE} when no external storage device was found. Typically,
185 * this is because the SD card is not mounted.
186 */
187 public final static int ERROR_DEVICE_NOT_FOUND = 1007;
188
Steve Howardb8e07a52010-07-21 14:53:21 -0700189 /**
Steve Howard33bbd122010-08-02 17:51:29 -0700190 * Value of {@link #COLUMN_ERROR_CODE} when some possibly transient error occurred but we can't
191 * resume the download.
192 */
193 public final static int ERROR_CANNOT_RESUME = 1008;
194
195 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700196 * Broadcast intent action sent by the download manager when a download completes.
197 */
198 public final static String ACTION_DOWNLOAD_COMPLETE = "android.intent.action.DOWNLOAD_COMPLETE";
199
200 /**
201 * Broadcast intent action sent by the download manager when a running download notification is
202 * clicked.
203 */
204 public final static String ACTION_NOTIFICATION_CLICKED =
205 "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED";
206
207 /**
208 * Intent extra included with {@link #ACTION_DOWNLOAD_COMPLETE} intents, indicating the ID (as a
209 * long) of the download that just completed.
210 */
211 public static final String EXTRA_DOWNLOAD_ID = "extra_download_id";
Steve Howarda2709362010-07-02 17:12:48 -0700212
213 // this array must contain all public columns
214 private static final String[] COLUMNS = new String[] {
215 COLUMN_ID,
216 COLUMN_TITLE,
217 COLUMN_DESCRIPTION,
218 COLUMN_URI,
219 COLUMN_MEDIA_TYPE,
220 COLUMN_TOTAL_SIZE_BYTES,
221 COLUMN_LOCAL_URI,
222 COLUMN_STATUS,
223 COLUMN_ERROR_CODE,
224 COLUMN_BYTES_DOWNLOADED_SO_FAR,
Steve Howardadcb6972010-07-12 17:09:25 -0700225 COLUMN_LAST_MODIFIED_TIMESTAMP
Steve Howarda2709362010-07-02 17:12:48 -0700226 };
227
228 // columns to request from DownloadProvider
229 private static final String[] UNDERLYING_COLUMNS = new String[] {
230 Downloads.Impl._ID,
231 Downloads.COLUMN_TITLE,
232 Downloads.COLUMN_DESCRIPTION,
233 Downloads.COLUMN_URI,
234 Downloads.COLUMN_MIME_TYPE,
235 Downloads.COLUMN_TOTAL_BYTES,
236 Downloads._DATA,
237 Downloads.COLUMN_STATUS,
Steve Howardadcb6972010-07-12 17:09:25 -0700238 Downloads.COLUMN_CURRENT_BYTES,
239 Downloads.COLUMN_LAST_MODIFICATION,
Steve Howarda2709362010-07-02 17:12:48 -0700240 };
241
242 private static final Set<String> LONG_COLUMNS = new HashSet<String>(
243 Arrays.asList(COLUMN_ID, COLUMN_TOTAL_SIZE_BYTES, COLUMN_STATUS, COLUMN_ERROR_CODE,
Steve Howardadcb6972010-07-12 17:09:25 -0700244 COLUMN_BYTES_DOWNLOADED_SO_FAR, COLUMN_LAST_MODIFIED_TIMESTAMP));
Steve Howarda2709362010-07-02 17:12:48 -0700245
246 /**
247 * This class contains all the information necessary to request a new download. The URI is the
248 * only required parameter.
249 */
250 public static class Request {
251 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700252 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
253 * {@link ConnectivityManager#TYPE_MOBILE}.
254 */
255 public static final int NETWORK_MOBILE = 1 << 0;
Steve Howarda2709362010-07-02 17:12:48 -0700256
Steve Howardb8e07a52010-07-21 14:53:21 -0700257 /**
258 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
259 * {@link ConnectivityManager#TYPE_WIFI}.
260 */
261 public static final int NETWORK_WIFI = 1 << 1;
262
263 /**
264 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
265 * {@link ConnectivityManager#TYPE_WIMAX}.
266 */
267 public static final int NETWORK_WIMAX = 1 << 2;
268
269 private Uri mUri;
270 private Uri mDestinationUri;
271 private Map<String, String> mRequestHeaders = new HashMap<String, String>();
272 private String mTitle;
273 private String mDescription;
Steve Howard8e15afe2010-07-28 17:12:40 -0700274 private boolean mShowNotification = true;
Steve Howarda2709362010-07-02 17:12:48 -0700275 private String mMediaType;
Steve Howardb8e07a52010-07-21 14:53:21 -0700276 private boolean mRoamingAllowed = true;
277 private int mAllowedNetworkTypes = ~0; // default to all network types allowed
Steve Howarda2709362010-07-02 17:12:48 -0700278
279 /**
280 * @param uri the HTTP URI to download.
281 */
282 public Request(Uri uri) {
283 if (uri == null) {
284 throw new NullPointerException();
285 }
286 String scheme = uri.getScheme();
287 if (scheme == null || !scheme.equals("http")) {
288 throw new IllegalArgumentException("Can only download HTTP URIs: " + uri);
289 }
290 mUri = uri;
291 }
292
293 /**
294 * Set the local destination for the downloaded data. Must be a file URI to a path on
295 * external storage, and the calling application must have the WRITE_EXTERNAL_STORAGE
296 * permission.
297 *
298 * By default, downloads are saved to a generated file in the download cache and may be
299 * deleted by the download manager at any time.
300 *
301 * @return this object
302 */
303 public Request setDestinationUri(Uri uri) {
304 mDestinationUri = uri;
305 return this;
306 }
307
308 /**
309 * Set an HTTP header to be included with the download request.
310 * @param header HTTP header name
311 * @param value header value
312 * @return this object
313 */
314 public Request setRequestHeader(String header, String value) {
315 mRequestHeaders.put(header, value);
316 return this;
317 }
318
319 /**
320 * Set the title of this download, to be displayed in notifications (if enabled)
321 * @return this object
322 */
323 public Request setTitle(String title) {
324 mTitle = title;
325 return this;
326 }
327
328 /**
329 * Set a description of this download, to be displayed in notifications (if enabled)
330 * @return this object
331 */
332 public Request setDescription(String description) {
333 mDescription = description;
334 return this;
335 }
336
337 /**
338 * Set the Internet Media Type of this download. This will override the media type declared
339 * in the server's response.
340 * @see <a href="http://www.ietf.org/rfc/rfc1590.txt">RFC 1590, defining Media Types</a>
341 * @return this object
342 */
343 public Request setMediaType(String mediaType) {
344 mMediaType = mediaType;
345 return this;
346 }
347
348 /**
Steve Howard8e15afe2010-07-28 17:12:40 -0700349 * Control whether a system notification is posted by the download manager while this
350 * download is running. If enabled, the download manager posts notifications about downloads
351 * through the system {@link android.app.NotificationManager}. By default, a notification is
352 * shown.
Steve Howarda2709362010-07-02 17:12:48 -0700353 *
Steve Howard8e15afe2010-07-28 17:12:40 -0700354 * If set to false, this requires the permission
355 * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
356 *
357 * @param show whether the download manager should show a notification for this download.
Steve Howarda2709362010-07-02 17:12:48 -0700358 * @return this object
Steve Howard8e15afe2010-07-28 17:12:40 -0700359 * @hide
Steve Howarda2709362010-07-02 17:12:48 -0700360 */
Steve Howard8e15afe2010-07-28 17:12:40 -0700361 public Request setShowRunningNotification(boolean show) {
362 mShowNotification = show;
Steve Howarda2709362010-07-02 17:12:48 -0700363 return this;
364 }
365
Steve Howardb8e07a52010-07-21 14:53:21 -0700366 /**
367 * Restrict the types of networks over which this download may proceed. By default, all
368 * network types are allowed.
369 * @param flags any combination of the NETWORK_* bit flags.
370 * @return this object
371 */
Steve Howarda2709362010-07-02 17:12:48 -0700372 public Request setAllowedNetworkTypes(int flags) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700373 mAllowedNetworkTypes = flags;
374 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700375 }
376
Steve Howardb8e07a52010-07-21 14:53:21 -0700377 /**
378 * Set whether this download may proceed over a roaming connection. By default, roaming is
379 * allowed.
380 * @param allowed whether to allow a roaming connection to be used
381 * @return this object
382 */
Steve Howarda2709362010-07-02 17:12:48 -0700383 public Request setAllowedOverRoaming(boolean allowed) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700384 mRoamingAllowed = allowed;
385 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700386 }
387
388 /**
389 * @return ContentValues to be passed to DownloadProvider.insert()
390 */
Steve Howardb8e07a52010-07-21 14:53:21 -0700391 ContentValues toContentValues(String packageName) {
Steve Howarda2709362010-07-02 17:12:48 -0700392 ContentValues values = new ContentValues();
393 assert mUri != null;
394 values.put(Downloads.COLUMN_URI, mUri.toString());
Steve Howardb8e07a52010-07-21 14:53:21 -0700395 values.put(Downloads.Impl.COLUMN_IS_PUBLIC_API, true);
396 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE, packageName);
Steve Howarda2709362010-07-02 17:12:48 -0700397
398 if (mDestinationUri != null) {
Steve Howardadcb6972010-07-12 17:09:25 -0700399 values.put(Downloads.COLUMN_DESTINATION, Downloads.Impl.DESTINATION_FILE_URI);
400 values.put(Downloads.COLUMN_FILE_NAME_HINT, mDestinationUri.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700401 } else {
402 values.put(Downloads.COLUMN_DESTINATION,
403 Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE);
404 }
405
406 if (!mRequestHeaders.isEmpty()) {
Steve Howardea9147d2010-07-13 19:02:45 -0700407 encodeHttpHeaders(values);
Steve Howarda2709362010-07-02 17:12:48 -0700408 }
409
410 putIfNonNull(values, Downloads.COLUMN_TITLE, mTitle);
411 putIfNonNull(values, Downloads.COLUMN_DESCRIPTION, mDescription);
412 putIfNonNull(values, Downloads.COLUMN_MIME_TYPE, mMediaType);
413
Steve Howard8e15afe2010-07-28 17:12:40 -0700414 values.put(Downloads.COLUMN_VISIBILITY,
415 mShowNotification ? Downloads.VISIBILITY_VISIBLE
416 : Downloads.VISIBILITY_HIDDEN);
Steve Howarda2709362010-07-02 17:12:48 -0700417
Steve Howardb8e07a52010-07-21 14:53:21 -0700418 values.put(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES, mAllowedNetworkTypes);
419 values.put(Downloads.Impl.COLUMN_ALLOW_ROAMING, mRoamingAllowed);
420
Steve Howarda2709362010-07-02 17:12:48 -0700421 return values;
422 }
423
Steve Howardea9147d2010-07-13 19:02:45 -0700424 private void encodeHttpHeaders(ContentValues values) {
425 int index = 0;
426 for (Map.Entry<String, String> entry : mRequestHeaders.entrySet()) {
427 String headerString = entry.getKey() + ": " + entry.getValue();
428 values.put(Downloads.Impl.RequestHeaders.INSERT_KEY_PREFIX + index, headerString);
429 index++;
430 }
431 }
432
Steve Howarda2709362010-07-02 17:12:48 -0700433 private void putIfNonNull(ContentValues contentValues, String key, String value) {
434 if (value != null) {
435 contentValues.put(key, value);
436 }
437 }
438 }
439
440 /**
441 * This class may be used to filter download manager queries.
442 */
443 public static class Query {
444 private Long mId;
445 private Integer mStatusFlags = null;
446
447 /**
448 * Include only the download with the given ID.
449 * @return this object
450 */
451 public Query setFilterById(long id) {
452 mId = id;
453 return this;
454 }
455
456 /**
457 * Include only downloads with status matching any the given status flags.
458 * @param flags any combination of the STATUS_* bit flags
459 * @return this object
460 */
461 public Query setFilterByStatus(int flags) {
462 mStatusFlags = flags;
463 return this;
464 }
465
466 /**
467 * Run this query using the given ContentResolver.
468 * @param projection the projection to pass to ContentResolver.query()
469 * @return the Cursor returned by ContentResolver.query()
470 */
471 Cursor runQuery(ContentResolver resolver, String[] projection) {
472 Uri uri = Downloads.CONTENT_URI;
473 String selection = null;
474
475 if (mId != null) {
476 uri = Uri.withAppendedPath(uri, mId.toString());
477 }
478
479 if (mStatusFlags != null) {
480 List<String> parts = new ArrayList<String>();
481 if ((mStatusFlags & STATUS_PENDING) != 0) {
482 parts.add(statusClause("=", Downloads.STATUS_PENDING));
483 }
484 if ((mStatusFlags & STATUS_RUNNING) != 0) {
485 parts.add(statusClause("=", Downloads.STATUS_RUNNING));
486 }
487 if ((mStatusFlags & STATUS_PAUSED) != 0) {
488 parts.add(statusClause("=", Downloads.STATUS_PENDING_PAUSED));
489 parts.add(statusClause("=", Downloads.STATUS_RUNNING_PAUSED));
490 }
491 if ((mStatusFlags & STATUS_SUCCESSFUL) != 0) {
492 parts.add(statusClause("=", Downloads.STATUS_SUCCESS));
493 }
494 if ((mStatusFlags & STATUS_FAILED) != 0) {
495 parts.add("(" + statusClause(">=", 400)
496 + " AND " + statusClause("<", 600) + ")");
497 }
498 selection = joinStrings(" OR ", parts);
Steve Howarda2709362010-07-02 17:12:48 -0700499 }
Steve Howardadcb6972010-07-12 17:09:25 -0700500 String orderBy = Downloads.COLUMN_LAST_MODIFICATION + " DESC";
501 return resolver.query(uri, projection, selection, null, orderBy);
Steve Howarda2709362010-07-02 17:12:48 -0700502 }
503
504 private String joinStrings(String joiner, Iterable<String> parts) {
505 StringBuilder builder = new StringBuilder();
506 boolean first = true;
507 for (String part : parts) {
508 if (!first) {
509 builder.append(joiner);
510 }
511 builder.append(part);
512 first = false;
513 }
514 return builder.toString();
515 }
516
517 private String statusClause(String operator, int value) {
518 return Downloads.COLUMN_STATUS + operator + "'" + value + "'";
519 }
520 }
521
522 private ContentResolver mResolver;
Steve Howardb8e07a52010-07-21 14:53:21 -0700523 private String mPackageName;
Steve Howarda2709362010-07-02 17:12:48 -0700524
525 /**
526 * @hide
527 */
Steve Howardb8e07a52010-07-21 14:53:21 -0700528 public DownloadManager(ContentResolver resolver, String packageName) {
Steve Howarda2709362010-07-02 17:12:48 -0700529 mResolver = resolver;
Steve Howardb8e07a52010-07-21 14:53:21 -0700530 mPackageName = packageName;
Steve Howarda2709362010-07-02 17:12:48 -0700531 }
532
533 /**
534 * Enqueue a new download. The download will start automatically once the download manager is
535 * ready to execute it and connectivity is available.
536 *
537 * @param request the parameters specifying this download
538 * @return an ID for the download, unique across the system. This ID is used to make future
539 * calls related to this download.
540 */
541 public long enqueue(Request request) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700542 ContentValues values = request.toContentValues(mPackageName);
Steve Howarda2709362010-07-02 17:12:48 -0700543 Uri downloadUri = mResolver.insert(Downloads.CONTENT_URI, values);
544 long id = Long.parseLong(downloadUri.getLastPathSegment());
545 return id;
546 }
547
548 /**
549 * Cancel a download and remove it from the download manager. The download will be stopped if
550 * it was running, and it will no longer be accessible through the download manager. If a file
551 * was already downloaded, it will not be deleted.
552 *
553 * @param id the ID of the download
554 */
555 public void remove(long id) {
556 int numDeleted = mResolver.delete(getDownloadUri(id), null, null);
557 if (numDeleted == 0) {
558 throw new IllegalArgumentException("Download " + id + " does not exist");
559 }
560 }
561
562 /**
563 * Query the download manager about downloads that have been requested.
564 * @param query parameters specifying filters for this query
565 * @return a Cursor over the result set of downloads, with columns consisting of all the
566 * COLUMN_* constants.
567 */
568 public Cursor query(Query query) {
569 Cursor underlyingCursor = query.runQuery(mResolver, UNDERLYING_COLUMNS);
570 return new CursorTranslator(underlyingCursor);
571 }
572
573 /**
574 * Open a downloaded file for reading. The download must have completed.
575 * @param id the ID of the download
576 * @return a read-only {@link ParcelFileDescriptor}
577 * @throws FileNotFoundException if the destination file does not already exist
578 */
579 public ParcelFileDescriptor openDownloadedFile(long id) throws FileNotFoundException {
580 return mResolver.openFileDescriptor(getDownloadUri(id), "r");
581 }
582
583 /**
584 * Get the DownloadProvider URI for the download with the given ID.
585 */
586 private Uri getDownloadUri(long id) {
587 Uri downloadUri = Uri.withAppendedPath(Downloads.CONTENT_URI, Long.toString(id));
588 return downloadUri;
589 }
590
591 /**
592 * This class wraps a cursor returned by DownloadProvider -- the "underlying cursor" -- and
593 * presents a different set of columns, those defined in the DownloadManager.COLUMN_* constants.
594 * Some columns correspond directly to underlying values while others are computed from
595 * underlying data.
596 */
597 private static class CursorTranslator extends CursorWrapper {
598 public CursorTranslator(Cursor cursor) {
599 super(cursor);
600 }
601
602 @Override
603 public int getColumnIndex(String columnName) {
604 return Arrays.asList(COLUMNS).indexOf(columnName);
605 }
606
607 @Override
608 public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException {
609 int index = getColumnIndex(columnName);
610 if (index == -1) {
611 throw new IllegalArgumentException();
612 }
613 return index;
614 }
615
616 @Override
617 public String getColumnName(int columnIndex) {
618 int numColumns = COLUMNS.length;
619 if (columnIndex < 0 || columnIndex >= numColumns) {
620 throw new IllegalArgumentException("Invalid column index " + columnIndex + ", "
621 + numColumns + " columns exist");
622 }
623 return COLUMNS[columnIndex];
624 }
625
626 @Override
627 public String[] getColumnNames() {
628 String[] returnColumns = new String[COLUMNS.length];
629 System.arraycopy(COLUMNS, 0, returnColumns, 0, COLUMNS.length);
630 return returnColumns;
631 }
632
633 @Override
634 public int getColumnCount() {
635 return COLUMNS.length;
636 }
637
638 @Override
639 public byte[] getBlob(int columnIndex) {
640 throw new UnsupportedOperationException();
641 }
642
643 @Override
644 public double getDouble(int columnIndex) {
645 return getLong(columnIndex);
646 }
647
648 private boolean isLongColumn(String column) {
649 return LONG_COLUMNS.contains(column);
650 }
651
652 @Override
653 public float getFloat(int columnIndex) {
654 return (float) getDouble(columnIndex);
655 }
656
657 @Override
658 public int getInt(int columnIndex) {
659 return (int) getLong(columnIndex);
660 }
661
662 @Override
663 public long getLong(int columnIndex) {
664 return translateLong(getColumnName(columnIndex));
665 }
666
667 @Override
668 public short getShort(int columnIndex) {
669 return (short) getLong(columnIndex);
670 }
671
672 @Override
673 public String getString(int columnIndex) {
674 return translateString(getColumnName(columnIndex));
675 }
676
677 private String translateString(String column) {
678 if (isLongColumn(column)) {
679 return Long.toString(translateLong(column));
680 }
681 if (column.equals(COLUMN_TITLE)) {
682 return getUnderlyingString(Downloads.COLUMN_TITLE);
683 }
684 if (column.equals(COLUMN_DESCRIPTION)) {
685 return getUnderlyingString(Downloads.COLUMN_DESCRIPTION);
686 }
687 if (column.equals(COLUMN_URI)) {
688 return getUnderlyingString(Downloads.COLUMN_URI);
689 }
690 if (column.equals(COLUMN_MEDIA_TYPE)) {
691 return getUnderlyingString(Downloads.COLUMN_MIME_TYPE);
692 }
Steve Howard8651bd52010-08-03 12:35:32 -0700693
Steve Howarda2709362010-07-02 17:12:48 -0700694 assert column.equals(COLUMN_LOCAL_URI);
Steve Howard8651bd52010-08-03 12:35:32 -0700695 String localUri = getUnderlyingString(Downloads._DATA);
696 if (localUri == null) {
697 return null;
698 }
699 return Uri.fromFile(new File(localUri)).toString();
Steve Howarda2709362010-07-02 17:12:48 -0700700 }
701
702 private long translateLong(String column) {
703 if (!isLongColumn(column)) {
704 // mimic behavior of underlying cursor -- most likely, throw NumberFormatException
705 return Long.valueOf(translateString(column));
706 }
707
708 if (column.equals(COLUMN_ID)) {
709 return getUnderlyingLong(Downloads.Impl._ID);
710 }
711 if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) {
712 return getUnderlyingLong(Downloads.COLUMN_TOTAL_BYTES);
713 }
714 if (column.equals(COLUMN_STATUS)) {
715 return translateStatus((int) getUnderlyingLong(Downloads.COLUMN_STATUS));
716 }
717 if (column.equals(COLUMN_ERROR_CODE)) {
718 return translateErrorCode((int) getUnderlyingLong(Downloads.COLUMN_STATUS));
719 }
720 if (column.equals(COLUMN_BYTES_DOWNLOADED_SO_FAR)) {
721 return getUnderlyingLong(Downloads.COLUMN_CURRENT_BYTES);
722 }
Steve Howardadcb6972010-07-12 17:09:25 -0700723 assert column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP);
724 return getUnderlyingLong(Downloads.COLUMN_LAST_MODIFICATION);
Steve Howarda2709362010-07-02 17:12:48 -0700725 }
726
727 private long translateErrorCode(int status) {
728 if (translateStatus(status) != STATUS_FAILED) {
729 return 0; // arbitrary value when status is not an error
730 }
Steve Howard33bbd122010-08-02 17:51:29 -0700731 if ((400 <= status && status < Downloads.Impl.MIN_ARTIFICIAL_ERROR_STATUS)
732 || (500 <= status && status < 600)) {
Steve Howarda2709362010-07-02 17:12:48 -0700733 // HTTP status code
734 return status;
735 }
736
737 switch (status) {
738 case Downloads.STATUS_FILE_ERROR:
739 return ERROR_FILE_ERROR;
740
741 case Downloads.STATUS_UNHANDLED_HTTP_CODE:
742 case Downloads.STATUS_UNHANDLED_REDIRECT:
743 return ERROR_UNHANDLED_HTTP_CODE;
744
745 case Downloads.STATUS_HTTP_DATA_ERROR:
746 return ERROR_HTTP_DATA_ERROR;
747
748 case Downloads.STATUS_TOO_MANY_REDIRECTS:
749 return ERROR_TOO_MANY_REDIRECTS;
750
751 case Downloads.STATUS_INSUFFICIENT_SPACE_ERROR:
752 return ERROR_INSUFFICIENT_SPACE;
753
754 case Downloads.STATUS_DEVICE_NOT_FOUND_ERROR:
755 return ERROR_DEVICE_NOT_FOUND;
756
Steve Howard33bbd122010-08-02 17:51:29 -0700757 case Downloads.Impl.STATUS_CANNOT_RESUME:
758 return ERROR_CANNOT_RESUME;
759
Steve Howarda2709362010-07-02 17:12:48 -0700760 default:
761 return ERROR_UNKNOWN;
762 }
763 }
764
765 private long getUnderlyingLong(String column) {
766 return super.getLong(super.getColumnIndex(column));
767 }
768
769 private String getUnderlyingString(String column) {
770 return super.getString(super.getColumnIndex(column));
771 }
772
773 private long translateStatus(int status) {
774 switch (status) {
775 case Downloads.STATUS_PENDING:
776 return STATUS_PENDING;
777
778 case Downloads.STATUS_RUNNING:
779 return STATUS_RUNNING;
780
781 case Downloads.STATUS_PENDING_PAUSED:
782 case Downloads.STATUS_RUNNING_PAUSED:
783 return STATUS_PAUSED;
784
785 case Downloads.STATUS_SUCCESS:
786 return STATUS_SUCCESSFUL;
787
788 default:
789 assert Downloads.isStatusError(status);
790 return STATUS_FAILED;
791 }
792 }
793 }
794}