blob: fb0e79b849b289c6238737454083b09872a74969 [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
Jeff Sharkey32cd2fb2013-10-02 10:11:22 -070019import android.annotation.SdkConstant;
20import android.annotation.SdkConstant.SdkConstantType;
Steve Howarda2709362010-07-02 17:12:48 -070021import android.content.ContentResolver;
Steve Howardeca77fc2010-09-12 18:49:08 -070022import android.content.ContentUris;
Steve Howarda2709362010-07-02 17:12:48 -070023import android.content.ContentValues;
Steve Howard4f564cd2010-09-22 15:57:25 -070024import android.content.Context;
Steve Howarda2709362010-07-02 17:12:48 -070025import android.database.Cursor;
26import android.database.CursorWrapper;
Steve Howardd58429f2010-09-27 16:32:39 -070027import android.net.ConnectivityManager;
Jeff Sharkey1a303952011-06-16 13:04:20 -070028import android.net.NetworkPolicyManager;
Steve Howardd58429f2010-09-27 16:32:39 -070029import android.net.Uri;
Steve Howard4f564cd2010-09-22 15:57:25 -070030import android.os.Environment;
Steve Howarda2709362010-07-02 17:12:48 -070031import android.os.ParcelFileDescriptor;
32import android.provider.Downloads;
Vasu Nori0abbf802011-01-17 15:08:14 -080033import android.provider.Settings;
34import android.provider.Settings.SettingNotFoundException;
Vasu Noric0e50752011-01-20 17:57:54 -080035import android.text.TextUtils;
Steve Howard4f564cd2010-09-22 15:57:25 -070036import android.util.Pair;
Steve Howarda2709362010-07-02 17:12:48 -070037
Steve Howard4f564cd2010-09-22 15:57:25 -070038import java.io.File;
Steve Howarda2709362010-07-02 17:12:48 -070039import java.io.FileNotFoundException;
40import java.util.ArrayList;
Steve Howarda2709362010-07-02 17:12:48 -070041import java.util.List;
Steve Howarda2709362010-07-02 17:12:48 -070042
43/**
44 * The download manager is a system service that handles long-running HTTP downloads. Clients may
45 * request that a URI be downloaded to a particular destination file. The download manager will
46 * conduct the download in the background, taking care of HTTP interactions and retrying downloads
47 * after failures or across connectivity changes and system reboots.
48 *
49 * Instances of this class should be obtained through
50 * {@link android.content.Context#getSystemService(String)} by passing
51 * {@link android.content.Context#DOWNLOAD_SERVICE}.
Steve Howard610c4352010-09-30 18:30:04 -070052 *
53 * Apps that request downloads through this API should register a broadcast receiver for
54 * {@link #ACTION_NOTIFICATION_CLICKED} to appropriately handle when the user clicks on a running
55 * download in a notification or from the downloads UI.
Nicolas Falliere9530e3a2012-06-18 17:21:06 -070056 *
57 * Note that the application must have the {@link android.Manifest.permission#INTERNET}
58 * permission to use this class.
Steve Howarda2709362010-07-02 17:12:48 -070059 */
60public class DownloadManager {
Vasu Norie7be6bd2010-10-10 14:58:08 -070061
Steve Howarda2709362010-07-02 17:12:48 -070062 /**
63 * An identifier for a particular download, unique across the system. Clients use this ID to
64 * make subsequent calls related to the download.
65 */
Vasu Norief7e33b2010-10-20 13:26:02 -070066 public final static String COLUMN_ID = Downloads.Impl._ID;
Steve Howarda2709362010-07-02 17:12:48 -070067
68 /**
Steve Howard8651bd52010-08-03 12:35:32 -070069 * The client-supplied title for this download. This will be displayed in system notifications.
70 * Defaults to the empty string.
Steve Howarda2709362010-07-02 17:12:48 -070071 */
Vasu Norief7e33b2010-10-20 13:26:02 -070072 public final static String COLUMN_TITLE = Downloads.Impl.COLUMN_TITLE;
Steve Howarda2709362010-07-02 17:12:48 -070073
74 /**
75 * The client-supplied description of this download. This will be displayed in system
Steve Howard8651bd52010-08-03 12:35:32 -070076 * notifications. Defaults to the empty string.
Steve Howarda2709362010-07-02 17:12:48 -070077 */
Vasu Norief7e33b2010-10-20 13:26:02 -070078 public final static String COLUMN_DESCRIPTION = Downloads.Impl.COLUMN_DESCRIPTION;
Steve Howarda2709362010-07-02 17:12:48 -070079
80 /**
81 * URI to be downloaded.
82 */
Vasu Norief7e33b2010-10-20 13:26:02 -070083 public final static String COLUMN_URI = Downloads.Impl.COLUMN_URI;
Steve Howarda2709362010-07-02 17:12:48 -070084
85 /**
Steve Howard8651bd52010-08-03 12:35:32 -070086 * Internet Media Type of the downloaded file. If no value is provided upon creation, this will
87 * initially be null and will be filled in based on the server's response once the download has
88 * started.
Steve Howarda2709362010-07-02 17:12:48 -070089 *
90 * @see <a href="http://www.ietf.org/rfc/rfc1590.txt">RFC 1590, defining Media Types</a>
91 */
92 public final static String COLUMN_MEDIA_TYPE = "media_type";
93
94 /**
Steve Howard8651bd52010-08-03 12:35:32 -070095 * Total size of the download in bytes. This will initially be -1 and will be filled in once
96 * the download starts.
Steve Howarda2709362010-07-02 17:12:48 -070097 */
98 public final static String COLUMN_TOTAL_SIZE_BYTES = "total_size";
99
100 /**
101 * Uri where downloaded file will be stored. If a destination is supplied by client, that URI
Steve Howard8651bd52010-08-03 12:35:32 -0700102 * will be used here. Otherwise, the value will initially be null and will be filled in with a
103 * generated URI once the download has started.
Steve Howarda2709362010-07-02 17:12:48 -0700104 */
105 public final static String COLUMN_LOCAL_URI = "local_uri";
106
107 /**
Doug Zongkeree04af32010-10-08 13:42:16 -0700108 * The pathname of the file where the download is stored.
109 */
110 public final static String COLUMN_LOCAL_FILENAME = "local_filename";
111
112 /**
Steve Howarda2709362010-07-02 17:12:48 -0700113 * Current status of the download, as one of the STATUS_* constants.
114 */
Vasu Norief7e33b2010-10-20 13:26:02 -0700115 public final static String COLUMN_STATUS = Downloads.Impl.COLUMN_STATUS;
Steve Howarda2709362010-07-02 17:12:48 -0700116
117 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700118 * Provides more detail on the status of the download. Its meaning depends on the value of
119 * {@link #COLUMN_STATUS}.
Steve Howarda2709362010-07-02 17:12:48 -0700120 *
Steve Howard3e8c1d32010-09-29 17:03:32 -0700121 * When {@link #COLUMN_STATUS} is {@link #STATUS_FAILED}, this indicates the type of error that
122 * occurred. If an HTTP error occurred, this will hold the HTTP status code as defined in RFC
123 * 2616. Otherwise, it will hold one of the ERROR_* constants.
124 *
125 * When {@link #COLUMN_STATUS} is {@link #STATUS_PAUSED}, this indicates why the download is
126 * paused. It will hold one of the PAUSED_* constants.
127 *
128 * If {@link #COLUMN_STATUS} is neither {@link #STATUS_FAILED} nor {@link #STATUS_PAUSED}, this
129 * column's value is undefined.
Steve Howarda2709362010-07-02 17:12:48 -0700130 *
131 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1.1">RFC 2616
132 * status codes</a>
133 */
Steve Howard3e8c1d32010-09-29 17:03:32 -0700134 public final static String COLUMN_REASON = "reason";
Steve Howarda2709362010-07-02 17:12:48 -0700135
136 /**
137 * Number of bytes download so far.
138 */
139 public final static String COLUMN_BYTES_DOWNLOADED_SO_FAR = "bytes_so_far";
140
141 /**
Steve Howardadcb6972010-07-12 17:09:25 -0700142 * Timestamp when the download was last modified, in {@link System#currentTimeMillis
Steve Howarda2709362010-07-02 17:12:48 -0700143 * System.currentTimeMillis()} (wall clock time in UTC).
144 */
Steve Howardadcb6972010-07-12 17:09:25 -0700145 public final static String COLUMN_LAST_MODIFIED_TIMESTAMP = "last_modified_timestamp";
Steve Howarda2709362010-07-02 17:12:48 -0700146
Vasu Nori216fa222010-10-12 23:08:13 -0700147 /**
148 * The URI to the corresponding entry in MediaProvider for this downloaded entry. It is
149 * used to delete the entries from MediaProvider database when it is deleted from the
150 * downloaded list.
151 */
Vasu Norief7e33b2010-10-20 13:26:02 -0700152 public static final String COLUMN_MEDIAPROVIDER_URI = Downloads.Impl.COLUMN_MEDIAPROVIDER_URI;
Steve Howarda2709362010-07-02 17:12:48 -0700153
154 /**
Jeff Sharkeyb180a652013-09-23 14:23:41 -0700155 * @hide
156 */
157 public final static String COLUMN_ALLOW_WRITE = Downloads.Impl.COLUMN_ALLOW_WRITE;
158
159 /**
Steve Howarda2709362010-07-02 17:12:48 -0700160 * Value of {@link #COLUMN_STATUS} when the download is waiting to start.
161 */
162 public final static int STATUS_PENDING = 1 << 0;
163
164 /**
165 * Value of {@link #COLUMN_STATUS} when the download is currently running.
166 */
167 public final static int STATUS_RUNNING = 1 << 1;
168
169 /**
170 * Value of {@link #COLUMN_STATUS} when the download is waiting to retry or resume.
171 */
172 public final static int STATUS_PAUSED = 1 << 2;
173
174 /**
175 * Value of {@link #COLUMN_STATUS} when the download has successfully completed.
176 */
177 public final static int STATUS_SUCCESSFUL = 1 << 3;
178
179 /**
180 * Value of {@link #COLUMN_STATUS} when the download has failed (and will not be retried).
181 */
182 public final static int STATUS_FAILED = 1 << 4;
183
Steve Howarda2709362010-07-02 17:12:48 -0700184 /**
185 * Value of COLUMN_ERROR_CODE when the download has completed with an error that doesn't fit
186 * under any other error code.
187 */
188 public final static int ERROR_UNKNOWN = 1000;
189
190 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700191 * Value of {@link #COLUMN_REASON} when a storage issue arises which doesn't fit under any
Steve Howarda2709362010-07-02 17:12:48 -0700192 * other error code. Use the more specific {@link #ERROR_INSUFFICIENT_SPACE} and
193 * {@link #ERROR_DEVICE_NOT_FOUND} when appropriate.
194 */
195 public final static int ERROR_FILE_ERROR = 1001;
196
197 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700198 * Value of {@link #COLUMN_REASON} when an HTTP code was received that download manager
Steve Howarda2709362010-07-02 17:12:48 -0700199 * can't handle.
200 */
201 public final static int ERROR_UNHANDLED_HTTP_CODE = 1002;
202
203 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700204 * Value of {@link #COLUMN_REASON} when an error receiving or processing data occurred at
Steve Howarda2709362010-07-02 17:12:48 -0700205 * the HTTP level.
206 */
207 public final static int ERROR_HTTP_DATA_ERROR = 1004;
208
209 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700210 * Value of {@link #COLUMN_REASON} when there were too many redirects.
Steve Howarda2709362010-07-02 17:12:48 -0700211 */
212 public final static int ERROR_TOO_MANY_REDIRECTS = 1005;
213
214 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700215 * Value of {@link #COLUMN_REASON} when there was insufficient storage space. Typically,
Steve Howarda2709362010-07-02 17:12:48 -0700216 * this is because the SD card is full.
217 */
218 public final static int ERROR_INSUFFICIENT_SPACE = 1006;
219
220 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700221 * Value of {@link #COLUMN_REASON} when no external storage device was found. Typically,
Steve Howarda2709362010-07-02 17:12:48 -0700222 * this is because the SD card is not mounted.
223 */
224 public final static int ERROR_DEVICE_NOT_FOUND = 1007;
225
Steve Howardb8e07a52010-07-21 14:53:21 -0700226 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700227 * Value of {@link #COLUMN_REASON} when some possibly transient error occurred but we can't
Steve Howard33bbd122010-08-02 17:51:29 -0700228 * resume the download.
229 */
230 public final static int ERROR_CANNOT_RESUME = 1008;
231
232 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700233 * Value of {@link #COLUMN_REASON} when the requested destination file already exists (the
Steve Howarda9e87c92010-09-16 12:02:03 -0700234 * download manager will not overwrite an existing file).
235 */
236 public final static int ERROR_FILE_ALREADY_EXISTS = 1009;
237
238 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700239 * Value of {@link #COLUMN_REASON} when the download has failed because of
240 * {@link NetworkPolicyManager} controls on the requesting application.
241 *
242 * @hide
243 */
244 public final static int ERROR_BLOCKED = 1010;
245
246 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700247 * Value of {@link #COLUMN_REASON} when the download is paused because some network error
248 * occurred and the download manager is waiting before retrying the request.
249 */
250 public final static int PAUSED_WAITING_TO_RETRY = 1;
251
252 /**
253 * Value of {@link #COLUMN_REASON} when the download is waiting for network connectivity to
254 * proceed.
255 */
256 public final static int PAUSED_WAITING_FOR_NETWORK = 2;
257
258 /**
259 * Value of {@link #COLUMN_REASON} when the download exceeds a size limit for downloads over
260 * the mobile network and the download manager is waiting for a Wi-Fi connection to proceed.
261 */
262 public final static int PAUSED_QUEUED_FOR_WIFI = 3;
263
264 /**
265 * Value of {@link #COLUMN_REASON} when the download is paused for some other reason.
266 */
267 public final static int PAUSED_UNKNOWN = 4;
268
269 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700270 * Broadcast intent action sent by the download manager when a download completes.
271 */
Jeff Sharkey32cd2fb2013-10-02 10:11:22 -0700272 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Steve Howardb8e07a52010-07-21 14:53:21 -0700273 public final static String ACTION_DOWNLOAD_COMPLETE = "android.intent.action.DOWNLOAD_COMPLETE";
274
275 /**
Steve Howard610c4352010-09-30 18:30:04 -0700276 * Broadcast intent action sent by the download manager when the user clicks on a running
277 * download, either from a system notification or from the downloads UI.
Steve Howardb8e07a52010-07-21 14:53:21 -0700278 */
Jeff Sharkey32cd2fb2013-10-02 10:11:22 -0700279 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Steve Howardb8e07a52010-07-21 14:53:21 -0700280 public final static String ACTION_NOTIFICATION_CLICKED =
281 "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED";
282
283 /**
Steve Howarde78fc182010-09-24 14:59:36 -0700284 * Intent action to launch an activity to display all downloads.
285 */
Jeff Sharkey32cd2fb2013-10-02 10:11:22 -0700286 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
Steve Howarde78fc182010-09-24 14:59:36 -0700287 public final static String ACTION_VIEW_DOWNLOADS = "android.intent.action.VIEW_DOWNLOADS";
288
289 /**
Vasu Norie5f92242011-01-24 16:12:20 -0800290 * Intent extra included with {@link #ACTION_VIEW_DOWNLOADS} to start DownloadApp in
291 * sort-by-size mode.
292 */
293 public final static String INTENT_EXTRAS_SORT_BY_SIZE =
294 "android.app.DownloadManager.extra_sortBySize";
295
296 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700297 * Intent extra included with {@link #ACTION_DOWNLOAD_COMPLETE} intents, indicating the ID (as a
298 * long) of the download that just completed.
299 */
300 public static final String EXTRA_DOWNLOAD_ID = "extra_download_id";
Steve Howarda2709362010-07-02 17:12:48 -0700301
Vasu Nori71b8c232010-10-27 15:22:19 -0700302 /**
303 * When clicks on multiple notifications are received, the following
304 * provides an array of download ids corresponding to the download notification that was
305 * clicked. It can be retrieved by the receiver of this
306 * Intent using {@link android.content.Intent#getLongArrayExtra(String)}.
307 */
308 public static final String EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS = "extra_click_download_ids";
309
Vasu Norie16c43b2010-11-06 18:48:08 -0700310 /**
311 * columns to request from DownloadProvider.
312 * @hide
313 */
314 public static final String[] UNDERLYING_COLUMNS = new String[] {
Steve Howarda2709362010-07-02 17:12:48 -0700315 Downloads.Impl._ID,
Vasu Norie69924f2010-11-15 13:10:11 -0800316 Downloads.Impl._DATA + " AS " + COLUMN_LOCAL_FILENAME,
Vasu Nori216fa222010-10-12 23:08:13 -0700317 Downloads.Impl.COLUMN_MEDIAPROVIDER_URI,
Vasu Nori5be894e2010-11-02 21:55:30 -0700318 Downloads.Impl.COLUMN_DESTINATION,
Vasu Norief7e33b2010-10-20 13:26:02 -0700319 Downloads.Impl.COLUMN_TITLE,
320 Downloads.Impl.COLUMN_DESCRIPTION,
321 Downloads.Impl.COLUMN_URI,
Vasu Norief7e33b2010-10-20 13:26:02 -0700322 Downloads.Impl.COLUMN_STATUS,
Steve Howarda9e87c92010-09-16 12:02:03 -0700323 Downloads.Impl.COLUMN_FILE_NAME_HINT,
Vasu Norie16c43b2010-11-06 18:48:08 -0700324 Downloads.Impl.COLUMN_MIME_TYPE + " AS " + COLUMN_MEDIA_TYPE,
325 Downloads.Impl.COLUMN_TOTAL_BYTES + " AS " + COLUMN_TOTAL_SIZE_BYTES,
326 Downloads.Impl.COLUMN_LAST_MODIFICATION + " AS " + COLUMN_LAST_MODIFIED_TIMESTAMP,
327 Downloads.Impl.COLUMN_CURRENT_BYTES + " AS " + COLUMN_BYTES_DOWNLOADED_SO_FAR,
Jeff Sharkeyb180a652013-09-23 14:23:41 -0700328 Downloads.Impl.COLUMN_ALLOW_WRITE,
Vasu Norie16c43b2010-11-06 18:48:08 -0700329 /* add the following 'computed' columns to the cursor.
330 * they are not 'returned' by the database, but their inclusion
331 * eliminates need to have lot of methods in CursorTranslator
332 */
333 "'placeholder' AS " + COLUMN_LOCAL_URI,
334 "'placeholder' AS " + COLUMN_REASON
Steve Howarda2709362010-07-02 17:12:48 -0700335 };
336
Steve Howarda2709362010-07-02 17:12:48 -0700337 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700338 * This class contains all the information necessary to request a new download. The URI is the
Steve Howarda2709362010-07-02 17:12:48 -0700339 * only required parameter.
Steve Howard4f564cd2010-09-22 15:57:25 -0700340 *
341 * Note that the default download destination is a shared volume where the system might delete
342 * your file if it needs to reclaim space for system use. If this is a problem, use a location
343 * on external storage (see {@link #setDestinationUri(Uri)}.
Steve Howarda2709362010-07-02 17:12:48 -0700344 */
345 public static class Request {
346 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700347 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
348 * {@link ConnectivityManager#TYPE_MOBILE}.
349 */
350 public static final int NETWORK_MOBILE = 1 << 0;
Steve Howarda2709362010-07-02 17:12:48 -0700351
Steve Howardb8e07a52010-07-21 14:53:21 -0700352 /**
353 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
354 * {@link ConnectivityManager#TYPE_WIFI}.
355 */
356 public static final int NETWORK_WIFI = 1 << 1;
357
HÃ¥kan3 Johansson011238b2012-02-08 21:13:35 +0100358 /**
359 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
360 * {@link ConnectivityManager#TYPE_BLUETOOTH}.
361 * @hide
362 */
363 public static final int NETWORK_BLUETOOTH = 1 << 2;
364
Steve Howardb8e07a52010-07-21 14:53:21 -0700365 private Uri mUri;
366 private Uri mDestinationUri;
Steve Howard4f564cd2010-09-22 15:57:25 -0700367 private List<Pair<String, String>> mRequestHeaders = new ArrayList<Pair<String, String>>();
368 private CharSequence mTitle;
369 private CharSequence mDescription;
Steve Howard4f564cd2010-09-22 15:57:25 -0700370 private String mMimeType;
Steve Howardb8e07a52010-07-21 14:53:21 -0700371 private int mAllowedNetworkTypes = ~0; // default to all network types allowed
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700372 private boolean mRoamingAllowed = true;
373 private boolean mMeteredAllowed = true;
Steve Howard90fb15a2010-09-09 16:13:41 -0700374 private boolean mIsVisibleInDownloadsUi = true;
Vasu Nori5be894e2010-11-02 21:55:30 -0700375 private boolean mScannable = false;
Vasu Norif83e6e42010-12-13 16:28:31 -0800376 private boolean mUseSystemCache = false;
Vasu Nori1cde3fb2010-11-05 11:02:52 -0700377 /** if a file is designated as a MediaScanner scannable file, the following value is
378 * stored in the database column {@link Downloads.Impl#COLUMN_MEDIA_SCANNED}.
379 */
380 private static final int SCANNABLE_VALUE_YES = 0;
381 // value of 1 is stored in the above column by DownloadProvider after it is scanned by
382 // MediaScanner
383 /** if a file is designated as a file that should not be scanned by MediaScanner,
384 * the following value is stored in the database column
385 * {@link Downloads.Impl#COLUMN_MEDIA_SCANNED}.
386 */
387 private static final int SCANNABLE_VALUE_NO = 2;
Steve Howarda2709362010-07-02 17:12:48 -0700388
389 /**
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700390 * This download is visible but only shows in the notifications
391 * while it's in progress.
392 */
393 public static final int VISIBILITY_VISIBLE = 0;
394
395 /**
396 * This download is visible and shows in the notifications while
397 * in progress and after completion.
398 */
399 public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED = 1;
400
401 /**
402 * This download doesn't show in the UI or in the notifications.
403 */
404 public static final int VISIBILITY_HIDDEN = 2;
405
Vasu Norif9e85232011-02-10 14:59:54 -0800406 /**
407 * This download shows in the notifications after completion ONLY.
408 * It is usuable only with
Vasu Nori37281302011-03-07 11:25:01 -0800409 * {@link DownloadManager#addCompletedDownload(String, String,
410 * boolean, String, String, long, boolean)}.
Vasu Norif9e85232011-02-10 14:59:54 -0800411 */
412 public static final int VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION = 3;
413
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700414 /** can take any of the following values: {@link #VISIBILITY_HIDDEN}
Vasu Norif9e85232011-02-10 14:59:54 -0800415 * {@link #VISIBILITY_VISIBLE_NOTIFY_COMPLETED}, {@link #VISIBILITY_VISIBLE},
416 * {@link #VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION}
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700417 */
418 private int mNotificationVisibility = VISIBILITY_VISIBLE;
419
420 /**
Alex Klyubin66629bc2015-06-11 14:34:44 -0700421 * @param uri the HTTP or HTTPS URI to download.
Steve Howarda2709362010-07-02 17:12:48 -0700422 */
423 public Request(Uri uri) {
424 if (uri == null) {
425 throw new NullPointerException();
426 }
427 String scheme = uri.getScheme();
Paul Westbrook86a60192010-09-15 12:55:49 -0700428 if (scheme == null || (!scheme.equals("http") && !scheme.equals("https"))) {
429 throw new IllegalArgumentException("Can only download HTTP/HTTPS URIs: " + uri);
Steve Howarda2709362010-07-02 17:12:48 -0700430 }
431 mUri = uri;
432 }
433
Vasu Noric0e50752011-01-20 17:57:54 -0800434 Request(String uriString) {
435 mUri = Uri.parse(uriString);
436 }
437
Steve Howarda2709362010-07-02 17:12:48 -0700438 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700439 * Set the local destination for the downloaded file. Must be a file URI to a path on
Steve Howarda2709362010-07-02 17:12:48 -0700440 * external storage, and the calling application must have the WRITE_EXTERNAL_STORAGE
441 * permission.
Vasu Nori5be894e2010-11-02 21:55:30 -0700442 * <p>
443 * The downloaded file is not scanned by MediaScanner.
444 * But it can be made scannable by calling {@link #allowScanningByMediaScanner()}.
445 * <p>
Steve Howard4f564cd2010-09-22 15:57:25 -0700446 * By default, downloads are saved to a generated filename in the shared download cache and
447 * may be deleted by the system at any time to reclaim space.
Steve Howarda2709362010-07-02 17:12:48 -0700448 *
449 * @return this object
450 */
451 public Request setDestinationUri(Uri uri) {
452 mDestinationUri = uri;
453 return this;
454 }
455
456 /**
Vasu Norif83e6e42010-12-13 16:28:31 -0800457 * Set the local destination for the downloaded file to the system cache dir (/cache).
458 * This is only available to System apps with the permission
459 * {@link android.Manifest.permission#ACCESS_CACHE_FILESYSTEM}.
460 * <p>
461 * The downloaded file is not scanned by MediaScanner.
462 * But it can be made scannable by calling {@link #allowScanningByMediaScanner()}.
463 * <p>
464 * Files downloaded to /cache may be deleted by the system at any time to reclaim space.
465 *
466 * @return this object
467 * @hide
468 */
469 public Request setDestinationToSystemCache() {
470 mUseSystemCache = true;
471 return this;
472 }
473
474 /**
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700475 * Set the local destination for the downloaded file to a path within
476 * the application's external files directory (as returned by
477 * {@link Context#getExternalFilesDir(String)}.
Vasu Nori5be894e2010-11-02 21:55:30 -0700478 * <p>
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700479 * The downloaded file is not scanned by MediaScanner. But it can be
480 * made scannable by calling {@link #allowScanningByMediaScanner()}.
Steve Howard4f564cd2010-09-22 15:57:25 -0700481 *
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700482 * @param context the {@link Context} to use in determining the external
483 * files directory
484 * @param dirType the directory type to pass to
485 * {@link Context#getExternalFilesDir(String)}
486 * @param subPath the path within the external directory, including the
487 * destination filename
Steve Howard4f564cd2010-09-22 15:57:25 -0700488 * @return this object
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700489 * @throws IllegalStateException If the external storage directory
490 * cannot be found or created.
Steve Howard4f564cd2010-09-22 15:57:25 -0700491 */
492 public Request setDestinationInExternalFilesDir(Context context, String dirType,
493 String subPath) {
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700494 final File file = context.getExternalFilesDir(dirType);
495 if (file == null) {
496 throw new IllegalStateException("Failed to get external storage files directory");
497 } else if (file.exists()) {
498 if (!file.isDirectory()) {
499 throw new IllegalStateException(file.getAbsolutePath() +
500 " already exists and is not a directory");
501 }
502 } else {
503 if (!file.mkdirs()) {
504 throw new IllegalStateException("Unable to create directory: "+
505 file.getAbsolutePath());
506 }
507 }
508 setDestinationFromBase(file, subPath);
Steve Howard4f564cd2010-09-22 15:57:25 -0700509 return this;
510 }
511
512 /**
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700513 * Set the local destination for the downloaded file to a path within
514 * the public external storage directory (as returned by
515 * {@link Environment#getExternalStoragePublicDirectory(String)}).
516 * <p>
517 * The downloaded file is not scanned by MediaScanner. But it can be
518 * made scannable by calling {@link #allowScanningByMediaScanner()}.
Steve Howard4f564cd2010-09-22 15:57:25 -0700519 *
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700520 * @param dirType the directory type to pass to {@link Environment#getExternalStoragePublicDirectory(String)}
521 * @param subPath the path within the external directory, including the
522 * destination filename
Steve Howard4f564cd2010-09-22 15:57:25 -0700523 * @return this object
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700524 * @throws IllegalStateException If the external storage directory
525 * cannot be found or created.
Steve Howard4f564cd2010-09-22 15:57:25 -0700526 */
527 public Request setDestinationInExternalPublicDir(String dirType, String subPath) {
Vasu Nori6916b032010-12-19 20:31:00 -0800528 File file = Environment.getExternalStoragePublicDirectory(dirType);
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700529 if (file == null) {
530 throw new IllegalStateException("Failed to get external storage public directory");
531 } else if (file.exists()) {
Vasu Nori6916b032010-12-19 20:31:00 -0800532 if (!file.isDirectory()) {
533 throw new IllegalStateException(file.getAbsolutePath() +
534 " already exists and is not a directory");
535 }
536 } else {
Roger Chen1740ada2012-12-17 13:31:17 +0800537 if (!file.mkdirs()) {
Vasu Nori6916b032010-12-19 20:31:00 -0800538 throw new IllegalStateException("Unable to create directory: "+
539 file.getAbsolutePath());
540 }
541 }
542 setDestinationFromBase(file, subPath);
Steve Howard4f564cd2010-09-22 15:57:25 -0700543 return this;
544 }
545
546 private void setDestinationFromBase(File base, String subPath) {
547 if (subPath == null) {
548 throw new NullPointerException("subPath cannot be null");
549 }
550 mDestinationUri = Uri.withAppendedPath(Uri.fromFile(base), subPath);
551 }
552
553 /**
Vasu Nori5be894e2010-11-02 21:55:30 -0700554 * If the file to be downloaded is to be scanned by MediaScanner, this method
555 * should be called before {@link DownloadManager#enqueue(Request)} is called.
556 */
557 public void allowScanningByMediaScanner() {
558 mScannable = true;
559 }
560
561 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700562 * Add an HTTP header to be included with the download request. The header will be added to
563 * the end of the list.
Steve Howarda2709362010-07-02 17:12:48 -0700564 * @param header HTTP header name
565 * @param value header value
566 * @return this object
Steve Howard4f564cd2010-09-22 15:57:25 -0700567 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2">HTTP/1.1
568 * Message Headers</a>
Steve Howarda2709362010-07-02 17:12:48 -0700569 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700570 public Request addRequestHeader(String header, String value) {
571 if (header == null) {
572 throw new NullPointerException("header cannot be null");
573 }
574 if (header.contains(":")) {
575 throw new IllegalArgumentException("header may not contain ':'");
576 }
577 if (value == null) {
578 value = "";
579 }
580 mRequestHeaders.add(Pair.create(header, value));
Steve Howarda2709362010-07-02 17:12:48 -0700581 return this;
582 }
583
584 /**
Steve Howard610c4352010-09-30 18:30:04 -0700585 * Set the title of this download, to be displayed in notifications (if enabled). If no
586 * title is given, a default one will be assigned based on the download filename, once the
587 * download starts.
Steve Howarda2709362010-07-02 17:12:48 -0700588 * @return this object
589 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700590 public Request setTitle(CharSequence title) {
Steve Howarda2709362010-07-02 17:12:48 -0700591 mTitle = title;
592 return this;
593 }
594
595 /**
596 * Set a description of this download, to be displayed in notifications (if enabled)
597 * @return this object
598 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700599 public Request setDescription(CharSequence description) {
Steve Howarda2709362010-07-02 17:12:48 -0700600 mDescription = description;
601 return this;
602 }
603
604 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700605 * Set the MIME content type of this download. This will override the content type declared
Steve Howarda2709362010-07-02 17:12:48 -0700606 * in the server's response.
Steve Howard4f564cd2010-09-22 15:57:25 -0700607 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7">HTTP/1.1
608 * Media Types</a>
Steve Howarda2709362010-07-02 17:12:48 -0700609 * @return this object
610 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700611 public Request setMimeType(String mimeType) {
612 mMimeType = mimeType;
Steve Howarda2709362010-07-02 17:12:48 -0700613 return this;
614 }
615
616 /**
Steve Howard8e15afe2010-07-28 17:12:40 -0700617 * Control whether a system notification is posted by the download manager while this
618 * download is running. If enabled, the download manager posts notifications about downloads
619 * through the system {@link android.app.NotificationManager}. By default, a notification is
620 * shown.
Steve Howarda2709362010-07-02 17:12:48 -0700621 *
Steve Howard8e15afe2010-07-28 17:12:40 -0700622 * If set to false, this requires the permission
623 * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
624 *
625 * @param show whether the download manager should show a notification for this download.
Steve Howarda2709362010-07-02 17:12:48 -0700626 * @return this object
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700627 * @deprecated use {@link #setNotificationVisibility(int)}
Steve Howarda2709362010-07-02 17:12:48 -0700628 */
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700629 @Deprecated
Steve Howard8e15afe2010-07-28 17:12:40 -0700630 public Request setShowRunningNotification(boolean show) {
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700631 return (show) ? setNotificationVisibility(VISIBILITY_VISIBLE) :
632 setNotificationVisibility(VISIBILITY_HIDDEN);
633 }
634
635 /**
636 * Control whether a system notification is posted by the download manager while this
637 * download is running or when it is completed.
638 * If enabled, the download manager posts notifications about downloads
639 * through the system {@link android.app.NotificationManager}.
640 * By default, a notification is shown only when the download is in progress.
641 *<p>
642 * It can take the following values: {@link #VISIBILITY_HIDDEN},
643 * {@link #VISIBILITY_VISIBLE},
644 * {@link #VISIBILITY_VISIBLE_NOTIFY_COMPLETED}.
645 *<p>
646 * If set to {@link #VISIBILITY_HIDDEN}, this requires the permission
647 * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
648 *
649 * @param visibility the visibility setting value
650 * @return this object
651 */
652 public Request setNotificationVisibility(int visibility) {
653 mNotificationVisibility = visibility;
Steve Howarda2709362010-07-02 17:12:48 -0700654 return this;
655 }
656
Steve Howardb8e07a52010-07-21 14:53:21 -0700657 /**
Jeff Sharkey792e0912012-04-16 11:52:18 -0700658 * Restrict the types of networks over which this download may proceed.
659 * By default, all network types are allowed. Consider using
660 * {@link #setAllowedOverMetered(boolean)} instead, since it's more
661 * flexible.
662 *
Steve Howardb8e07a52010-07-21 14:53:21 -0700663 * @param flags any combination of the NETWORK_* bit flags.
664 * @return this object
665 */
Steve Howarda2709362010-07-02 17:12:48 -0700666 public Request setAllowedNetworkTypes(int flags) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700667 mAllowedNetworkTypes = flags;
668 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700669 }
670
Steve Howardb8e07a52010-07-21 14:53:21 -0700671 /**
672 * Set whether this download may proceed over a roaming connection. By default, roaming is
673 * allowed.
674 * @param allowed whether to allow a roaming connection to be used
675 * @return this object
676 */
Steve Howarda2709362010-07-02 17:12:48 -0700677 public Request setAllowedOverRoaming(boolean allowed) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700678 mRoamingAllowed = allowed;
679 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700680 }
681
682 /**
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700683 * Set whether this download may proceed over a metered network
684 * connection. By default, metered networks are allowed.
685 *
686 * @see ConnectivityManager#isActiveNetworkMetered()
687 */
688 public Request setAllowedOverMetered(boolean allow) {
689 mMeteredAllowed = allow;
690 return this;
691 }
692
693 /**
Steve Howard90fb15a2010-09-09 16:13:41 -0700694 * Set whether this download should be displayed in the system's Downloads UI. True by
695 * default.
696 * @param isVisible whether to display this download in the Downloads UI
697 * @return this object
698 */
699 public Request setVisibleInDownloadsUi(boolean isVisible) {
700 mIsVisibleInDownloadsUi = isVisible;
701 return this;
702 }
703
704 /**
Steve Howarda2709362010-07-02 17:12:48 -0700705 * @return ContentValues to be passed to DownloadProvider.insert()
706 */
Steve Howardb8e07a52010-07-21 14:53:21 -0700707 ContentValues toContentValues(String packageName) {
Steve Howarda2709362010-07-02 17:12:48 -0700708 ContentValues values = new ContentValues();
709 assert mUri != null;
Vasu Norief7e33b2010-10-20 13:26:02 -0700710 values.put(Downloads.Impl.COLUMN_URI, mUri.toString());
Steve Howardb8e07a52010-07-21 14:53:21 -0700711 values.put(Downloads.Impl.COLUMN_IS_PUBLIC_API, true);
Vasu Norief7e33b2010-10-20 13:26:02 -0700712 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE, packageName);
Steve Howarda2709362010-07-02 17:12:48 -0700713
714 if (mDestinationUri != null) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700715 values.put(Downloads.Impl.COLUMN_DESTINATION, Downloads.Impl.DESTINATION_FILE_URI);
716 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, mDestinationUri.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700717 } else {
Vasu Norief7e33b2010-10-20 13:26:02 -0700718 values.put(Downloads.Impl.COLUMN_DESTINATION,
Vasu Norif83e6e42010-12-13 16:28:31 -0800719 (this.mUseSystemCache) ?
720 Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION :
721 Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE);
Steve Howarda2709362010-07-02 17:12:48 -0700722 }
Vasu Nori5be894e2010-11-02 21:55:30 -0700723 // is the file supposed to be media-scannable?
Vasu Nori1cde3fb2010-11-05 11:02:52 -0700724 values.put(Downloads.Impl.COLUMN_MEDIA_SCANNED, (mScannable) ? SCANNABLE_VALUE_YES :
725 SCANNABLE_VALUE_NO);
Steve Howarda2709362010-07-02 17:12:48 -0700726
727 if (!mRequestHeaders.isEmpty()) {
Steve Howardea9147d2010-07-13 19:02:45 -0700728 encodeHttpHeaders(values);
Steve Howarda2709362010-07-02 17:12:48 -0700729 }
730
Vasu Norief7e33b2010-10-20 13:26:02 -0700731 putIfNonNull(values, Downloads.Impl.COLUMN_TITLE, mTitle);
732 putIfNonNull(values, Downloads.Impl.COLUMN_DESCRIPTION, mDescription);
733 putIfNonNull(values, Downloads.Impl.COLUMN_MIME_TYPE, mMimeType);
Steve Howarda2709362010-07-02 17:12:48 -0700734
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700735 values.put(Downloads.Impl.COLUMN_VISIBILITY, mNotificationVisibility);
Steve Howardb8e07a52010-07-21 14:53:21 -0700736 values.put(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES, mAllowedNetworkTypes);
737 values.put(Downloads.Impl.COLUMN_ALLOW_ROAMING, mRoamingAllowed);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700738 values.put(Downloads.Impl.COLUMN_ALLOW_METERED, mMeteredAllowed);
Steve Howard90fb15a2010-09-09 16:13:41 -0700739 values.put(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, mIsVisibleInDownloadsUi);
Steve Howardb8e07a52010-07-21 14:53:21 -0700740
Steve Howarda2709362010-07-02 17:12:48 -0700741 return values;
742 }
743
Steve Howardea9147d2010-07-13 19:02:45 -0700744 private void encodeHttpHeaders(ContentValues values) {
745 int index = 0;
Steve Howard4f564cd2010-09-22 15:57:25 -0700746 for (Pair<String, String> header : mRequestHeaders) {
747 String headerString = header.first + ": " + header.second;
Steve Howardea9147d2010-07-13 19:02:45 -0700748 values.put(Downloads.Impl.RequestHeaders.INSERT_KEY_PREFIX + index, headerString);
749 index++;
750 }
751 }
752
Steve Howard4f564cd2010-09-22 15:57:25 -0700753 private void putIfNonNull(ContentValues contentValues, String key, Object value) {
Steve Howarda2709362010-07-02 17:12:48 -0700754 if (value != null) {
Steve Howard4f564cd2010-09-22 15:57:25 -0700755 contentValues.put(key, value.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700756 }
757 }
758 }
759
760 /**
761 * This class may be used to filter download manager queries.
762 */
763 public static class Query {
Steve Howardf054e192010-09-01 18:26:26 -0700764 /**
765 * Constant for use with {@link #orderBy}
766 * @hide
767 */
768 public static final int ORDER_ASCENDING = 1;
769
770 /**
771 * Constant for use with {@link #orderBy}
772 * @hide
773 */
774 public static final int ORDER_DESCENDING = 2;
775
Steve Howard64c48b82010-10-07 17:53:52 -0700776 private long[] mIds = null;
Steve Howarda2709362010-07-02 17:12:48 -0700777 private Integer mStatusFlags = null;
Vasu Norief7e33b2010-10-20 13:26:02 -0700778 private String mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
Steve Howardf054e192010-09-01 18:26:26 -0700779 private int mOrderDirection = ORDER_DESCENDING;
Steve Howard90fb15a2010-09-09 16:13:41 -0700780 private boolean mOnlyIncludeVisibleInDownloadsUi = false;
Steve Howarda2709362010-07-02 17:12:48 -0700781
782 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700783 * Include only the downloads with the given IDs.
Steve Howarda2709362010-07-02 17:12:48 -0700784 * @return this object
785 */
Steve Howard64c48b82010-10-07 17:53:52 -0700786 public Query setFilterById(long... ids) {
787 mIds = ids;
Steve Howarda2709362010-07-02 17:12:48 -0700788 return this;
789 }
790
791 /**
792 * Include only downloads with status matching any the given status flags.
793 * @param flags any combination of the STATUS_* bit flags
794 * @return this object
795 */
796 public Query setFilterByStatus(int flags) {
797 mStatusFlags = flags;
798 return this;
799 }
800
801 /**
Steve Howard90fb15a2010-09-09 16:13:41 -0700802 * Controls whether this query includes downloads not visible in the system's Downloads UI.
803 * @param value if true, this query will only include downloads that should be displayed in
804 * the system's Downloads UI; if false (the default), this query will include
805 * both visible and invisible downloads.
806 * @return this object
807 * @hide
808 */
809 public Query setOnlyIncludeVisibleInDownloadsUi(boolean value) {
810 mOnlyIncludeVisibleInDownloadsUi = value;
811 return this;
812 }
813
814 /**
Steve Howardf054e192010-09-01 18:26:26 -0700815 * Change the sort order of the returned Cursor.
816 *
817 * @param column one of the COLUMN_* constants; currently, only
818 * {@link #COLUMN_LAST_MODIFIED_TIMESTAMP} and {@link #COLUMN_TOTAL_SIZE_BYTES} are
819 * supported.
820 * @param direction either {@link #ORDER_ASCENDING} or {@link #ORDER_DESCENDING}
821 * @return this object
822 * @hide
823 */
824 public Query orderBy(String column, int direction) {
825 if (direction != ORDER_ASCENDING && direction != ORDER_DESCENDING) {
826 throw new IllegalArgumentException("Invalid direction: " + direction);
827 }
828
829 if (column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP)) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700830 mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
Steve Howardf054e192010-09-01 18:26:26 -0700831 } else if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700832 mOrderByColumn = Downloads.Impl.COLUMN_TOTAL_BYTES;
Steve Howardf054e192010-09-01 18:26:26 -0700833 } else {
834 throw new IllegalArgumentException("Cannot order by " + column);
835 }
836 mOrderDirection = direction;
837 return this;
838 }
839
840 /**
Steve Howarda2709362010-07-02 17:12:48 -0700841 * Run this query using the given ContentResolver.
842 * @param projection the projection to pass to ContentResolver.query()
843 * @return the Cursor returned by ContentResolver.query()
844 */
Steve Howardeca77fc2010-09-12 18:49:08 -0700845 Cursor runQuery(ContentResolver resolver, String[] projection, Uri baseUri) {
846 Uri uri = baseUri;
Steve Howard90fb15a2010-09-09 16:13:41 -0700847 List<String> selectionParts = new ArrayList<String>();
Steve Howard64c48b82010-10-07 17:53:52 -0700848 String[] selectionArgs = null;
Steve Howarda2709362010-07-02 17:12:48 -0700849
Steve Howard64c48b82010-10-07 17:53:52 -0700850 if (mIds != null) {
851 selectionParts.add(getWhereClauseForIds(mIds));
852 selectionArgs = getWhereArgsForIds(mIds);
Steve Howarda2709362010-07-02 17:12:48 -0700853 }
854
855 if (mStatusFlags != null) {
856 List<String> parts = new ArrayList<String>();
857 if ((mStatusFlags & STATUS_PENDING) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700858 parts.add(statusClause("=", Downloads.Impl.STATUS_PENDING));
Steve Howarda2709362010-07-02 17:12:48 -0700859 }
860 if ((mStatusFlags & STATUS_RUNNING) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700861 parts.add(statusClause("=", Downloads.Impl.STATUS_RUNNING));
Steve Howarda2709362010-07-02 17:12:48 -0700862 }
863 if ((mStatusFlags & STATUS_PAUSED) != 0) {
Steve Howard3e8c1d32010-09-29 17:03:32 -0700864 parts.add(statusClause("=", Downloads.Impl.STATUS_PAUSED_BY_APP));
865 parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_TO_RETRY));
866 parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_FOR_NETWORK));
867 parts.add(statusClause("=", Downloads.Impl.STATUS_QUEUED_FOR_WIFI));
Steve Howarda2709362010-07-02 17:12:48 -0700868 }
869 if ((mStatusFlags & STATUS_SUCCESSFUL) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700870 parts.add(statusClause("=", Downloads.Impl.STATUS_SUCCESS));
Steve Howarda2709362010-07-02 17:12:48 -0700871 }
872 if ((mStatusFlags & STATUS_FAILED) != 0) {
873 parts.add("(" + statusClause(">=", 400)
874 + " AND " + statusClause("<", 600) + ")");
875 }
Steve Howard90fb15a2010-09-09 16:13:41 -0700876 selectionParts.add(joinStrings(" OR ", parts));
Steve Howarda2709362010-07-02 17:12:48 -0700877 }
Steve Howardf054e192010-09-01 18:26:26 -0700878
Steve Howard90fb15a2010-09-09 16:13:41 -0700879 if (mOnlyIncludeVisibleInDownloadsUi) {
880 selectionParts.add(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI + " != '0'");
881 }
882
Vasu Nori216fa222010-10-12 23:08:13 -0700883 // only return rows which are not marked 'deleted = 1'
884 selectionParts.add(Downloads.Impl.COLUMN_DELETED + " != '1'");
885
Steve Howard90fb15a2010-09-09 16:13:41 -0700886 String selection = joinStrings(" AND ", selectionParts);
Steve Howardf054e192010-09-01 18:26:26 -0700887 String orderDirection = (mOrderDirection == ORDER_ASCENDING ? "ASC" : "DESC");
888 String orderBy = mOrderByColumn + " " + orderDirection;
889
Steve Howard64c48b82010-10-07 17:53:52 -0700890 return resolver.query(uri, projection, selection, selectionArgs, orderBy);
Steve Howarda2709362010-07-02 17:12:48 -0700891 }
892
893 private String joinStrings(String joiner, Iterable<String> parts) {
894 StringBuilder builder = new StringBuilder();
895 boolean first = true;
896 for (String part : parts) {
897 if (!first) {
898 builder.append(joiner);
899 }
900 builder.append(part);
901 first = false;
902 }
903 return builder.toString();
904 }
905
906 private String statusClause(String operator, int value) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700907 return Downloads.Impl.COLUMN_STATUS + operator + "'" + value + "'";
Steve Howarda2709362010-07-02 17:12:48 -0700908 }
909 }
910
911 private ContentResolver mResolver;
Steve Howardb8e07a52010-07-21 14:53:21 -0700912 private String mPackageName;
Steve Howardeca77fc2010-09-12 18:49:08 -0700913 private Uri mBaseUri = Downloads.Impl.CONTENT_URI;
Steve Howarda2709362010-07-02 17:12:48 -0700914
915 /**
916 * @hide
917 */
Steve Howardb8e07a52010-07-21 14:53:21 -0700918 public DownloadManager(ContentResolver resolver, String packageName) {
Steve Howarda2709362010-07-02 17:12:48 -0700919 mResolver = resolver;
Steve Howardb8e07a52010-07-21 14:53:21 -0700920 mPackageName = packageName;
Steve Howarda2709362010-07-02 17:12:48 -0700921 }
922
923 /**
Steve Howardeca77fc2010-09-12 18:49:08 -0700924 * Makes this object access the download provider through /all_downloads URIs rather than
925 * /my_downloads URIs, for clients that have permission to do so.
926 * @hide
927 */
928 public void setAccessAllDownloads(boolean accessAllDownloads) {
929 if (accessAllDownloads) {
930 mBaseUri = Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI;
931 } else {
932 mBaseUri = Downloads.Impl.CONTENT_URI;
933 }
934 }
935
936 /**
Steve Howarda2709362010-07-02 17:12:48 -0700937 * Enqueue a new download. The download will start automatically once the download manager is
938 * ready to execute it and connectivity is available.
939 *
940 * @param request the parameters specifying this download
941 * @return an ID for the download, unique across the system. This ID is used to make future
942 * calls related to this download.
943 */
944 public long enqueue(Request request) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700945 ContentValues values = request.toContentValues(mPackageName);
Vasu Norief7e33b2010-10-20 13:26:02 -0700946 Uri downloadUri = mResolver.insert(Downloads.Impl.CONTENT_URI, values);
Steve Howarda2709362010-07-02 17:12:48 -0700947 long id = Long.parseLong(downloadUri.getLastPathSegment());
948 return id;
949 }
950
951 /**
Vasu Nori216fa222010-10-12 23:08:13 -0700952 * Marks the specified download as 'to be deleted'. This is done when a completed download
953 * is to be removed but the row was stored without enough info to delete the corresponding
954 * metadata from Mediaprovider database. Actual cleanup of this row is done in DownloadService.
955 *
956 * @param ids the IDs of the downloads to be marked 'deleted'
957 * @return the number of downloads actually updated
958 * @hide
959 */
960 public int markRowDeleted(long... ids) {
961 if (ids == null || ids.length == 0) {
962 // called with nothing to remove!
963 throw new IllegalArgumentException("input param 'ids' can't be null");
964 }
965 ContentValues values = new ContentValues();
966 values.put(Downloads.Impl.COLUMN_DELETED, 1);
Vasu Nori8da7a4e2010-11-17 17:14:49 -0800967 // if only one id is passed in, then include it in the uri itself.
968 // this will eliminate a full database scan in the download service.
969 if (ids.length == 1) {
970 return mResolver.update(ContentUris.withAppendedId(mBaseUri, ids[0]), values,
971 null, null);
972 }
Vasu Nori216fa222010-10-12 23:08:13 -0700973 return mResolver.update(mBaseUri, values, getWhereClauseForIds(ids),
974 getWhereArgsForIds(ids));
975 }
976
977 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700978 * Cancel downloads and remove them from the download manager. Each download will be stopped if
Vasu Nori17ee56c2011-02-28 08:35:39 -0800979 * it was running, and it will no longer be accessible through the download manager.
980 * If there is a downloaded file, partial or complete, it is deleted.
Steve Howarda2709362010-07-02 17:12:48 -0700981 *
Steve Howard64c48b82010-10-07 17:53:52 -0700982 * @param ids the IDs of the downloads to remove
983 * @return the number of downloads actually removed
Steve Howarda2709362010-07-02 17:12:48 -0700984 */
Steve Howard64c48b82010-10-07 17:53:52 -0700985 public int remove(long... ids) {
Vasu Norie16c43b2010-11-06 18:48:08 -0700986 return markRowDeleted(ids);
Steve Howarda2709362010-07-02 17:12:48 -0700987 }
988
989 /**
990 * Query the download manager about downloads that have been requested.
991 * @param query parameters specifying filters for this query
992 * @return a Cursor over the result set of downloads, with columns consisting of all the
993 * COLUMN_* constants.
994 */
995 public Cursor query(Query query) {
Steve Howardeca77fc2010-09-12 18:49:08 -0700996 Cursor underlyingCursor = query.runQuery(mResolver, UNDERLYING_COLUMNS, mBaseUri);
Steve Howardf054e192010-09-01 18:26:26 -0700997 if (underlyingCursor == null) {
998 return null;
999 }
Steve Howardeca77fc2010-09-12 18:49:08 -07001000 return new CursorTranslator(underlyingCursor, mBaseUri);
Steve Howarda2709362010-07-02 17:12:48 -07001001 }
1002
1003 /**
1004 * Open a downloaded file for reading. The download must have completed.
1005 * @param id the ID of the download
1006 * @return a read-only {@link ParcelFileDescriptor}
1007 * @throws FileNotFoundException if the destination file does not already exist
1008 */
1009 public ParcelFileDescriptor openDownloadedFile(long id) throws FileNotFoundException {
1010 return mResolver.openFileDescriptor(getDownloadUri(id), "r");
1011 }
1012
1013 /**
John Spurlock92a262c2013-11-04 16:25:38 -05001014 * Returns the {@link Uri} of the given downloaded file id, if the file is
1015 * downloaded successfully. Otherwise, null is returned.
Vasu Nori5be894e2010-11-02 21:55:30 -07001016 *
1017 * @param id the id of the downloaded file.
Jeff Sharkeyb11683b2015-07-29 10:15:34 -07001018 * @return the {@link Uri} of the given downloaded file id, if download was
1019 * successful. null otherwise.
Vasu Nori5be894e2010-11-02 21:55:30 -07001020 */
1021 public Uri getUriForDownloadedFile(long id) {
1022 // to check if the file is in cache, get its destination from the database
1023 Query query = new Query().setFilterById(id);
1024 Cursor cursor = null;
1025 try {
1026 cursor = query(query);
1027 if (cursor == null) {
1028 return null;
1029 }
Leon Scrogginsd75e64a2010-12-13 15:48:40 -05001030 if (cursor.moveToFirst()) {
Vasu Nori6e2b2a62010-11-16 17:58:22 -08001031 int status = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_STATUS));
Vasu Nori5be894e2010-11-02 21:55:30 -07001032 if (DownloadManager.STATUS_SUCCESSFUL == status) {
Jeff Sharkeyb11683b2015-07-29 10:15:34 -07001033 return ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI, id);
Vasu Nori5be894e2010-11-02 21:55:30 -07001034 }
1035 }
1036 } finally {
1037 if (cursor != null) {
1038 cursor.close();
1039 }
1040 }
1041 // downloaded file not found or its status is not 'successfully completed'
1042 return null;
1043 }
1044
1045 /**
John Spurlock92a262c2013-11-04 16:25:38 -05001046 * Returns the media type of the given downloaded file id, if the file was
1047 * downloaded successfully. Otherwise, null is returned.
Vasu Nori6e2b2a62010-11-16 17:58:22 -08001048 *
1049 * @param id the id of the downloaded file.
John Spurlock92a262c2013-11-04 16:25:38 -05001050 * @return the media type of the given downloaded file id, if download was successful. null
Vasu Nori6e2b2a62010-11-16 17:58:22 -08001051 * otherwise.
1052 */
1053 public String getMimeTypeForDownloadedFile(long id) {
1054 Query query = new Query().setFilterById(id);
1055 Cursor cursor = null;
1056 try {
1057 cursor = query(query);
1058 if (cursor == null) {
1059 return null;
1060 }
1061 while (cursor.moveToFirst()) {
1062 return cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_MEDIA_TYPE));
1063 }
1064 } finally {
1065 if (cursor != null) {
1066 cursor.close();
1067 }
1068 }
1069 // downloaded file not found or its status is not 'successfully completed'
1070 return null;
1071 }
1072
1073 /**
Steve Howard64c48b82010-10-07 17:53:52 -07001074 * Restart the given downloads, which must have already completed (successfully or not). This
Steve Howard90fb15a2010-09-09 16:13:41 -07001075 * method will only work when called from within the download manager's process.
Steve Howard64c48b82010-10-07 17:53:52 -07001076 * @param ids the IDs of the downloads
Steve Howard90fb15a2010-09-09 16:13:41 -07001077 * @hide
1078 */
Steve Howard64c48b82010-10-07 17:53:52 -07001079 public void restartDownload(long... ids) {
1080 Cursor cursor = query(new Query().setFilterById(ids));
Steve Howard90fb15a2010-09-09 16:13:41 -07001081 try {
Steve Howard64c48b82010-10-07 17:53:52 -07001082 for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
1083 int status = cursor.getInt(cursor.getColumnIndex(COLUMN_STATUS));
1084 if (status != STATUS_SUCCESSFUL && status != STATUS_FAILED) {
1085 throw new IllegalArgumentException("Cannot restart incomplete download: "
1086 + cursor.getLong(cursor.getColumnIndex(COLUMN_ID)));
1087 }
Steve Howard90fb15a2010-09-09 16:13:41 -07001088 }
1089 } finally {
1090 cursor.close();
1091 }
1092
1093 ContentValues values = new ContentValues();
1094 values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, 0);
1095 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, -1);
1096 values.putNull(Downloads.Impl._DATA);
1097 values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING);
Jeff Sharkey54781202013-01-17 17:27:33 -08001098 values.put(Downloads.Impl.COLUMN_FAILED_CONNECTIONS, 0);
Steve Howard64c48b82010-10-07 17:53:52 -07001099 mResolver.update(mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
Steve Howard90fb15a2010-09-09 16:13:41 -07001100 }
1101
1102 /**
Vasu Nori0abbf802011-01-17 15:08:14 -08001103 * Returns maximum size, in bytes, of downloads that may go over a mobile connection; or null if
1104 * there's no limit
1105 *
1106 * @param context the {@link Context} to use for accessing the {@link ContentResolver}
1107 * @return maximum size, in bytes, of downloads that may go over a mobile connection; or null if
1108 * there's no limit
1109 */
1110 public static Long getMaxBytesOverMobile(Context context) {
1111 try {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001112 return Settings.Global.getLong(context.getContentResolver(),
1113 Settings.Global.DOWNLOAD_MAX_BYTES_OVER_MOBILE);
Vasu Nori0abbf802011-01-17 15:08:14 -08001114 } catch (SettingNotFoundException exc) {
1115 return null;
1116 }
1117 }
1118
1119 /**
1120 * Returns recommended maximum size, in bytes, of downloads that may go over a mobile
1121 * connection; or null if there's no recommended limit. The user will have the option to bypass
1122 * this limit.
1123 *
1124 * @param context the {@link Context} to use for accessing the {@link ContentResolver}
1125 * @return recommended maximum size, in bytes, of downloads that may go over a mobile
1126 * connection; or null if there's no recommended limit.
1127 */
1128 public static Long getRecommendedMaxBytesOverMobile(Context context) {
1129 try {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001130 return Settings.Global.getLong(context.getContentResolver(),
1131 Settings.Global.DOWNLOAD_RECOMMENDED_MAX_BYTES_OVER_MOBILE);
Vasu Nori0abbf802011-01-17 15:08:14 -08001132 } catch (SettingNotFoundException exc) {
1133 return null;
1134 }
1135 }
Vasu Noric0e50752011-01-20 17:57:54 -08001136
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001137 /** {@hide} */
1138 public static boolean isActiveNetworkExpensive(Context context) {
1139 // TODO: connect to NetworkPolicyManager
1140 return false;
1141 }
1142
1143 /** {@hide} */
1144 public static long getActiveNetworkWarningBytes(Context context) {
1145 // TODO: connect to NetworkPolicyManager
1146 return -1;
1147 }
1148
Vasu Noric0e50752011-01-20 17:57:54 -08001149 /**
1150 * Adds a file to the downloads database system, so it could appear in Downloads App
1151 * (and thus become eligible for management by the Downloads App).
1152 * <p>
1153 * It is helpful to make the file scannable by MediaScanner by setting the param
1154 * isMediaScannerScannable to true. It makes the file visible in media managing
1155 * applications such as Gallery App, which could be a useful purpose of using this API.
1156 *
1157 * @param title the title that would appear for this file in Downloads App.
1158 * @param description the description that would appear for this file in Downloads App.
1159 * @param isMediaScannerScannable true if the file is to be scanned by MediaScanner. Files
1160 * scanned by MediaScanner appear in the applications used to view media (for example,
1161 * Gallery app).
1162 * @param mimeType mimetype of the file.
1163 * @param path absolute pathname to the file. The file should be world-readable, so that it can
1164 * be managed by the Downloads App and any other app that is used to read it (for example,
1165 * Gallery app to display the file, if the file contents represent a video/image).
1166 * @param length length of the downloaded file
Vasu Norif9e85232011-02-10 14:59:54 -08001167 * @param showNotification true if a notification is to be sent, false otherwise
Vasu Noric0e50752011-01-20 17:57:54 -08001168 * @return an ID for the download entry added to the downloads app, unique across the system
1169 * This ID is used to make future calls related to this download.
1170 */
Vasu Nori37281302011-03-07 11:25:01 -08001171 public long addCompletedDownload(String title, String description,
Vasu Norif9e85232011-02-10 14:59:54 -08001172 boolean isMediaScannerScannable, String mimeType, String path, long length,
1173 boolean showNotification) {
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001174 return addCompletedDownload(title, description, isMediaScannerScannable, mimeType, path,
1175 length, showNotification, false);
1176 }
1177
1178 /** {@hide} */
1179 public long addCompletedDownload(String title, String description,
1180 boolean isMediaScannerScannable, String mimeType, String path, long length,
1181 boolean showNotification, boolean allowWrite) {
Vasu Noric0e50752011-01-20 17:57:54 -08001182 // make sure the input args are non-null/non-zero
1183 validateArgumentIsNonEmpty("title", title);
1184 validateArgumentIsNonEmpty("description", description);
1185 validateArgumentIsNonEmpty("path", path);
1186 validateArgumentIsNonEmpty("mimeType", mimeType);
Jeff Sharkey33f95ed2012-05-02 17:07:54 -07001187 if (length < 0) {
Vasu Noric0e50752011-01-20 17:57:54 -08001188 throw new IllegalArgumentException(" invalid value for param: totalBytes");
1189 }
1190
1191 // if there is already an entry with the given path name in downloads.db, return its id
1192 Request request = new Request(NON_DOWNLOADMANAGER_DOWNLOAD)
1193 .setTitle(title)
1194 .setDescription(description)
1195 .setMimeType(mimeType);
1196 ContentValues values = request.toContentValues(null);
1197 values.put(Downloads.Impl.COLUMN_DESTINATION,
1198 Downloads.Impl.DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD);
1199 values.put(Downloads.Impl._DATA, path);
1200 values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_SUCCESS);
1201 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, length);
1202 values.put(Downloads.Impl.COLUMN_MEDIA_SCANNED,
1203 (isMediaScannerScannable) ? Request.SCANNABLE_VALUE_YES :
1204 Request.SCANNABLE_VALUE_NO);
Vasu Norif9e85232011-02-10 14:59:54 -08001205 values.put(Downloads.Impl.COLUMN_VISIBILITY, (showNotification) ?
1206 Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION : Request.VISIBILITY_HIDDEN);
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001207 values.put(Downloads.Impl.COLUMN_ALLOW_WRITE, allowWrite ? 1 : 0);
Vasu Noric0e50752011-01-20 17:57:54 -08001208 Uri downloadUri = mResolver.insert(Downloads.Impl.CONTENT_URI, values);
1209 if (downloadUri == null) {
1210 return -1;
1211 }
1212 return Long.parseLong(downloadUri.getLastPathSegment());
1213 }
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001214
Vasu Noric0e50752011-01-20 17:57:54 -08001215 private static final String NON_DOWNLOADMANAGER_DOWNLOAD =
1216 "non-dwnldmngr-download-dont-retry2download";
1217
1218 private static void validateArgumentIsNonEmpty(String paramName, String val) {
1219 if (TextUtils.isEmpty(val)) {
1220 throw new IllegalArgumentException(paramName + " can't be null");
1221 }
1222 }
1223
Vasu Nori0abbf802011-01-17 15:08:14 -08001224 /**
Steve Howarda2709362010-07-02 17:12:48 -07001225 * Get the DownloadProvider URI for the download with the given ID.
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001226 *
1227 * @hide
Steve Howarda2709362010-07-02 17:12:48 -07001228 */
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001229 public Uri getDownloadUri(long id) {
Steve Howardeca77fc2010-09-12 18:49:08 -07001230 return ContentUris.withAppendedId(mBaseUri, id);
Steve Howarda2709362010-07-02 17:12:48 -07001231 }
1232
1233 /**
Steve Howard64c48b82010-10-07 17:53:52 -07001234 * Get a parameterized SQL WHERE clause to select a bunch of IDs.
1235 */
1236 static String getWhereClauseForIds(long[] ids) {
1237 StringBuilder whereClause = new StringBuilder();
Vasu Norie7be6bd2010-10-10 14:58:08 -07001238 whereClause.append("(");
Steve Howard64c48b82010-10-07 17:53:52 -07001239 for (int i = 0; i < ids.length; i++) {
1240 if (i > 0) {
Vasu Norie7be6bd2010-10-10 14:58:08 -07001241 whereClause.append("OR ");
Steve Howard64c48b82010-10-07 17:53:52 -07001242 }
Vasu Norie7be6bd2010-10-10 14:58:08 -07001243 whereClause.append(Downloads.Impl._ID);
1244 whereClause.append(" = ? ");
Steve Howard64c48b82010-10-07 17:53:52 -07001245 }
1246 whereClause.append(")");
1247 return whereClause.toString();
1248 }
1249
1250 /**
1251 * Get the selection args for a clause returned by {@link #getWhereClauseForIds(long[])}.
1252 */
1253 static String[] getWhereArgsForIds(long[] ids) {
1254 String[] whereArgs = new String[ids.length];
1255 for (int i = 0; i < ids.length; i++) {
1256 whereArgs[i] = Long.toString(ids[i]);
1257 }
1258 return whereArgs;
1259 }
1260
1261 /**
Steve Howarda2709362010-07-02 17:12:48 -07001262 * This class wraps a cursor returned by DownloadProvider -- the "underlying cursor" -- and
1263 * presents a different set of columns, those defined in the DownloadManager.COLUMN_* constants.
1264 * Some columns correspond directly to underlying values while others are computed from
1265 * underlying data.
1266 */
1267 private static class CursorTranslator extends CursorWrapper {
Steve Howardeca77fc2010-09-12 18:49:08 -07001268 private Uri mBaseUri;
1269
1270 public CursorTranslator(Cursor cursor, Uri baseUri) {
Steve Howarda2709362010-07-02 17:12:48 -07001271 super(cursor);
Steve Howardeca77fc2010-09-12 18:49:08 -07001272 mBaseUri = baseUri;
Steve Howarda2709362010-07-02 17:12:48 -07001273 }
1274
1275 @Override
Steve Howarda2709362010-07-02 17:12:48 -07001276 public int getInt(int columnIndex) {
1277 return (int) getLong(columnIndex);
1278 }
1279
1280 @Override
1281 public long getLong(int columnIndex) {
Vasu Norie16c43b2010-11-06 18:48:08 -07001282 if (getColumnName(columnIndex).equals(COLUMN_REASON)) {
1283 return getReason(super.getInt(getColumnIndex(Downloads.Impl.COLUMN_STATUS)));
1284 } else if (getColumnName(columnIndex).equals(COLUMN_STATUS)) {
1285 return translateStatus(super.getInt(getColumnIndex(Downloads.Impl.COLUMN_STATUS)));
1286 } else {
1287 return super.getLong(columnIndex);
1288 }
Steve Howarda2709362010-07-02 17:12:48 -07001289 }
1290
1291 @Override
1292 public String getString(int columnIndex) {
Vasu Norie16c43b2010-11-06 18:48:08 -07001293 return (getColumnName(columnIndex).equals(COLUMN_LOCAL_URI)) ? getLocalUri() :
1294 super.getString(columnIndex);
Steve Howardeca77fc2010-09-12 18:49:08 -07001295 }
1296
1297 private String getLocalUri() {
Vasu Norie16c43b2010-11-06 18:48:08 -07001298 long destinationType = getLong(getColumnIndex(Downloads.Impl.COLUMN_DESTINATION));
1299 if (destinationType == Downloads.Impl.DESTINATION_FILE_URI ||
Vasu Noric0e50752011-01-20 17:57:54 -08001300 destinationType == Downloads.Impl.DESTINATION_EXTERNAL ||
1301 destinationType == Downloads.Impl.DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD) {
Vasu Nori98f03072010-11-15 17:22:20 -08001302 String localPath = getString(getColumnIndex(COLUMN_LOCAL_FILENAME));
Steve Howard99047d72010-09-29 17:41:37 -07001303 if (localPath == null) {
1304 return null;
1305 }
1306 return Uri.fromFile(new File(localPath)).toString();
Steve Howardbb0d23b2010-09-22 18:56:29 -07001307 }
1308
Steve Howardeca77fc2010-09-12 18:49:08 -07001309 // return content URI for cache download
Vasu Norie16c43b2010-11-06 18:48:08 -07001310 long downloadId = getLong(getColumnIndex(Downloads.Impl._ID));
Steve Howardeca77fc2010-09-12 18:49:08 -07001311 return ContentUris.withAppendedId(mBaseUri, downloadId).toString();
Steve Howarda2709362010-07-02 17:12:48 -07001312 }
1313
Steve Howard3e8c1d32010-09-29 17:03:32 -07001314 private long getReason(int status) {
1315 switch (translateStatus(status)) {
1316 case STATUS_FAILED:
1317 return getErrorCode(status);
1318
1319 case STATUS_PAUSED:
1320 return getPausedReason(status);
1321
1322 default:
1323 return 0; // arbitrary value when status is not an error
Steve Howarda2709362010-07-02 17:12:48 -07001324 }
Steve Howard3e8c1d32010-09-29 17:03:32 -07001325 }
1326
1327 private long getPausedReason(int status) {
1328 switch (status) {
1329 case Downloads.Impl.STATUS_WAITING_TO_RETRY:
1330 return PAUSED_WAITING_TO_RETRY;
1331
1332 case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
1333 return PAUSED_WAITING_FOR_NETWORK;
1334
1335 case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
1336 return PAUSED_QUEUED_FOR_WIFI;
1337
1338 default:
1339 return PAUSED_UNKNOWN;
1340 }
1341 }
1342
1343 private long getErrorCode(int status) {
Steve Howard33bbd122010-08-02 17:51:29 -07001344 if ((400 <= status && status < Downloads.Impl.MIN_ARTIFICIAL_ERROR_STATUS)
1345 || (500 <= status && status < 600)) {
Steve Howarda2709362010-07-02 17:12:48 -07001346 // HTTP status code
1347 return status;
1348 }
1349
1350 switch (status) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001351 case Downloads.Impl.STATUS_FILE_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001352 return ERROR_FILE_ERROR;
1353
Vasu Norief7e33b2010-10-20 13:26:02 -07001354 case Downloads.Impl.STATUS_UNHANDLED_HTTP_CODE:
1355 case Downloads.Impl.STATUS_UNHANDLED_REDIRECT:
Steve Howarda2709362010-07-02 17:12:48 -07001356 return ERROR_UNHANDLED_HTTP_CODE;
1357
Vasu Norief7e33b2010-10-20 13:26:02 -07001358 case Downloads.Impl.STATUS_HTTP_DATA_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001359 return ERROR_HTTP_DATA_ERROR;
1360
Vasu Norief7e33b2010-10-20 13:26:02 -07001361 case Downloads.Impl.STATUS_TOO_MANY_REDIRECTS:
Steve Howarda2709362010-07-02 17:12:48 -07001362 return ERROR_TOO_MANY_REDIRECTS;
1363
Vasu Norief7e33b2010-10-20 13:26:02 -07001364 case Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001365 return ERROR_INSUFFICIENT_SPACE;
1366
Vasu Norief7e33b2010-10-20 13:26:02 -07001367 case Downloads.Impl.STATUS_DEVICE_NOT_FOUND_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001368 return ERROR_DEVICE_NOT_FOUND;
1369
Steve Howard33bbd122010-08-02 17:51:29 -07001370 case Downloads.Impl.STATUS_CANNOT_RESUME:
1371 return ERROR_CANNOT_RESUME;
1372
Steve Howarda9e87c92010-09-16 12:02:03 -07001373 case Downloads.Impl.STATUS_FILE_ALREADY_EXISTS_ERROR:
1374 return ERROR_FILE_ALREADY_EXISTS;
1375
Steve Howarda2709362010-07-02 17:12:48 -07001376 default:
1377 return ERROR_UNKNOWN;
1378 }
1379 }
1380
Steve Howard3e8c1d32010-09-29 17:03:32 -07001381 private int translateStatus(int status) {
Steve Howarda2709362010-07-02 17:12:48 -07001382 switch (status) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001383 case Downloads.Impl.STATUS_PENDING:
Steve Howarda2709362010-07-02 17:12:48 -07001384 return STATUS_PENDING;
1385
Vasu Norief7e33b2010-10-20 13:26:02 -07001386 case Downloads.Impl.STATUS_RUNNING:
Steve Howarda2709362010-07-02 17:12:48 -07001387 return STATUS_RUNNING;
1388
Steve Howard3e8c1d32010-09-29 17:03:32 -07001389 case Downloads.Impl.STATUS_PAUSED_BY_APP:
1390 case Downloads.Impl.STATUS_WAITING_TO_RETRY:
1391 case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
1392 case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
Steve Howarda2709362010-07-02 17:12:48 -07001393 return STATUS_PAUSED;
1394
Vasu Norief7e33b2010-10-20 13:26:02 -07001395 case Downloads.Impl.STATUS_SUCCESS:
Steve Howarda2709362010-07-02 17:12:48 -07001396 return STATUS_SUCCESSFUL;
1397
1398 default:
Vasu Norief7e33b2010-10-20 13:26:02 -07001399 assert Downloads.Impl.isStatusError(status);
Steve Howarda2709362010-07-02 17:12:48 -07001400 return STATUS_FAILED;
1401 }
1402 }
1403 }
1404}