blob: 1e5f00727e12f36a9307d62ed1d4d0612b559333 [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;
Jeff Sharkey60cfad82016-01-05 17:30:57 -070030import android.os.Build;
Steve Howard4f564cd2010-09-22 15:57:25 -070031import android.os.Environment;
Steve Howarda2709362010-07-02 17:12:48 -070032import android.os.ParcelFileDescriptor;
33import android.provider.Downloads;
Vasu Nori0abbf802011-01-17 15:08:14 -080034import android.provider.Settings;
35import android.provider.Settings.SettingNotFoundException;
Vasu Noric0e50752011-01-20 17:57:54 -080036import android.text.TextUtils;
Steve Howard4f564cd2010-09-22 15:57:25 -070037import android.util.Pair;
Steve Howarda2709362010-07-02 17:12:48 -070038
Steve Howard4f564cd2010-09-22 15:57:25 -070039import java.io.File;
Steve Howarda2709362010-07-02 17:12:48 -070040import java.io.FileNotFoundException;
41import java.util.ArrayList;
Steve Howarda2709362010-07-02 17:12:48 -070042import java.util.List;
Steve Howarda2709362010-07-02 17:12:48 -070043
44/**
45 * The download manager is a system service that handles long-running HTTP downloads. Clients may
46 * request that a URI be downloaded to a particular destination file. The download manager will
47 * conduct the download in the background, taking care of HTTP interactions and retrying downloads
48 * after failures or across connectivity changes and system reboots.
49 *
50 * Instances of this class should be obtained through
51 * {@link android.content.Context#getSystemService(String)} by passing
52 * {@link android.content.Context#DOWNLOAD_SERVICE}.
Steve Howard610c4352010-09-30 18:30:04 -070053 *
54 * Apps that request downloads through this API should register a broadcast receiver for
55 * {@link #ACTION_NOTIFICATION_CLICKED} to appropriately handle when the user clicks on a running
56 * download in a notification or from the downloads UI.
Nicolas Falliere9530e3a2012-06-18 17:21:06 -070057 *
58 * Note that the application must have the {@link android.Manifest.permission#INTERNET}
59 * permission to use this class.
Steve Howarda2709362010-07-02 17:12:48 -070060 */
61public class DownloadManager {
Vasu Norie7be6bd2010-10-10 14:58:08 -070062
Steve Howarda2709362010-07-02 17:12:48 -070063 /**
64 * An identifier for a particular download, unique across the system. Clients use this ID to
65 * make subsequent calls related to the download.
66 */
Vasu Norief7e33b2010-10-20 13:26:02 -070067 public final static String COLUMN_ID = Downloads.Impl._ID;
Steve Howarda2709362010-07-02 17:12:48 -070068
69 /**
Steve Howard8651bd52010-08-03 12:35:32 -070070 * The client-supplied title for this download. This will be displayed in system notifications.
71 * Defaults to the empty string.
Steve Howarda2709362010-07-02 17:12:48 -070072 */
Vasu Norief7e33b2010-10-20 13:26:02 -070073 public final static String COLUMN_TITLE = Downloads.Impl.COLUMN_TITLE;
Steve Howarda2709362010-07-02 17:12:48 -070074
75 /**
76 * The client-supplied description of this download. This will be displayed in system
Steve Howard8651bd52010-08-03 12:35:32 -070077 * notifications. Defaults to the empty string.
Steve Howarda2709362010-07-02 17:12:48 -070078 */
Vasu Norief7e33b2010-10-20 13:26:02 -070079 public final static String COLUMN_DESCRIPTION = Downloads.Impl.COLUMN_DESCRIPTION;
Steve Howarda2709362010-07-02 17:12:48 -070080
81 /**
82 * URI to be downloaded.
83 */
Vasu Norief7e33b2010-10-20 13:26:02 -070084 public final static String COLUMN_URI = Downloads.Impl.COLUMN_URI;
Steve Howarda2709362010-07-02 17:12:48 -070085
86 /**
Steve Howard8651bd52010-08-03 12:35:32 -070087 * Internet Media Type of the downloaded file. If no value is provided upon creation, this will
88 * initially be null and will be filled in based on the server's response once the download has
89 * started.
Steve Howarda2709362010-07-02 17:12:48 -070090 *
91 * @see <a href="http://www.ietf.org/rfc/rfc1590.txt">RFC 1590, defining Media Types</a>
92 */
93 public final static String COLUMN_MEDIA_TYPE = "media_type";
94
95 /**
Steve Howard8651bd52010-08-03 12:35:32 -070096 * Total size of the download in bytes. This will initially be -1 and will be filled in once
97 * the download starts.
Steve Howarda2709362010-07-02 17:12:48 -070098 */
99 public final static String COLUMN_TOTAL_SIZE_BYTES = "total_size";
100
101 /**
102 * Uri where downloaded file will be stored. If a destination is supplied by client, that URI
Steve Howard8651bd52010-08-03 12:35:32 -0700103 * will be used here. Otherwise, the value will initially be null and will be filled in with a
104 * generated URI once the download has started.
Steve Howarda2709362010-07-02 17:12:48 -0700105 */
106 public final static String COLUMN_LOCAL_URI = "local_uri";
107
108 /**
Jeff Sharkey60cfad82016-01-05 17:30:57 -0700109 * Path to the downloaded file on disk.
110 * <p>
111 * Note that apps may not have filesystem permissions to directly access
112 * this path. Instead of trying to open this path directly, apps should use
113 * {@link ContentResolver#openFileDescriptor(Uri, String)} to gain access.
114 *
115 * @deprecated apps should transition to using
116 * {@link ContentResolver#openFileDescriptor(Uri, String)}
117 * instead.
Doug Zongkeree04af32010-10-08 13:42:16 -0700118 */
Jeff Sharkey60cfad82016-01-05 17:30:57 -0700119 @Deprecated
Doug Zongkeree04af32010-10-08 13:42:16 -0700120 public final static String COLUMN_LOCAL_FILENAME = "local_filename";
121
122 /**
Steve Howarda2709362010-07-02 17:12:48 -0700123 * Current status of the download, as one of the STATUS_* constants.
124 */
Vasu Norief7e33b2010-10-20 13:26:02 -0700125 public final static String COLUMN_STATUS = Downloads.Impl.COLUMN_STATUS;
Steve Howarda2709362010-07-02 17:12:48 -0700126
127 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700128 * Provides more detail on the status of the download. Its meaning depends on the value of
129 * {@link #COLUMN_STATUS}.
Steve Howarda2709362010-07-02 17:12:48 -0700130 *
Steve Howard3e8c1d32010-09-29 17:03:32 -0700131 * When {@link #COLUMN_STATUS} is {@link #STATUS_FAILED}, this indicates the type of error that
132 * occurred. If an HTTP error occurred, this will hold the HTTP status code as defined in RFC
133 * 2616. Otherwise, it will hold one of the ERROR_* constants.
134 *
135 * When {@link #COLUMN_STATUS} is {@link #STATUS_PAUSED}, this indicates why the download is
136 * paused. It will hold one of the PAUSED_* constants.
137 *
138 * If {@link #COLUMN_STATUS} is neither {@link #STATUS_FAILED} nor {@link #STATUS_PAUSED}, this
139 * column's value is undefined.
Steve Howarda2709362010-07-02 17:12:48 -0700140 *
141 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1.1">RFC 2616
142 * status codes</a>
143 */
Steve Howard3e8c1d32010-09-29 17:03:32 -0700144 public final static String COLUMN_REASON = "reason";
Steve Howarda2709362010-07-02 17:12:48 -0700145
146 /**
147 * Number of bytes download so far.
148 */
149 public final static String COLUMN_BYTES_DOWNLOADED_SO_FAR = "bytes_so_far";
150
151 /**
Steve Howardadcb6972010-07-12 17:09:25 -0700152 * Timestamp when the download was last modified, in {@link System#currentTimeMillis
Steve Howarda2709362010-07-02 17:12:48 -0700153 * System.currentTimeMillis()} (wall clock time in UTC).
154 */
Steve Howardadcb6972010-07-12 17:09:25 -0700155 public final static String COLUMN_LAST_MODIFIED_TIMESTAMP = "last_modified_timestamp";
Steve Howarda2709362010-07-02 17:12:48 -0700156
Vasu Nori216fa222010-10-12 23:08:13 -0700157 /**
158 * The URI to the corresponding entry in MediaProvider for this downloaded entry. It is
159 * used to delete the entries from MediaProvider database when it is deleted from the
160 * downloaded list.
161 */
Vasu Norief7e33b2010-10-20 13:26:02 -0700162 public static final String COLUMN_MEDIAPROVIDER_URI = Downloads.Impl.COLUMN_MEDIAPROVIDER_URI;
Steve Howarda2709362010-07-02 17:12:48 -0700163
164 /**
Jeff Sharkeyb180a652013-09-23 14:23:41 -0700165 * @hide
166 */
167 public final static String COLUMN_ALLOW_WRITE = Downloads.Impl.COLUMN_ALLOW_WRITE;
168
169 /**
Steve Howarda2709362010-07-02 17:12:48 -0700170 * Value of {@link #COLUMN_STATUS} when the download is waiting to start.
171 */
172 public final static int STATUS_PENDING = 1 << 0;
173
174 /**
175 * Value of {@link #COLUMN_STATUS} when the download is currently running.
176 */
177 public final static int STATUS_RUNNING = 1 << 1;
178
179 /**
180 * Value of {@link #COLUMN_STATUS} when the download is waiting to retry or resume.
181 */
182 public final static int STATUS_PAUSED = 1 << 2;
183
184 /**
185 * Value of {@link #COLUMN_STATUS} when the download has successfully completed.
186 */
187 public final static int STATUS_SUCCESSFUL = 1 << 3;
188
189 /**
190 * Value of {@link #COLUMN_STATUS} when the download has failed (and will not be retried).
191 */
192 public final static int STATUS_FAILED = 1 << 4;
193
Steve Howarda2709362010-07-02 17:12:48 -0700194 /**
195 * Value of COLUMN_ERROR_CODE when the download has completed with an error that doesn't fit
196 * under any other error code.
197 */
198 public final static int ERROR_UNKNOWN = 1000;
199
200 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700201 * Value of {@link #COLUMN_REASON} when a storage issue arises which doesn't fit under any
Steve Howarda2709362010-07-02 17:12:48 -0700202 * other error code. Use the more specific {@link #ERROR_INSUFFICIENT_SPACE} and
203 * {@link #ERROR_DEVICE_NOT_FOUND} when appropriate.
204 */
205 public final static int ERROR_FILE_ERROR = 1001;
206
207 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700208 * Value of {@link #COLUMN_REASON} when an HTTP code was received that download manager
Steve Howarda2709362010-07-02 17:12:48 -0700209 * can't handle.
210 */
211 public final static int ERROR_UNHANDLED_HTTP_CODE = 1002;
212
213 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700214 * Value of {@link #COLUMN_REASON} when an error receiving or processing data occurred at
Steve Howarda2709362010-07-02 17:12:48 -0700215 * the HTTP level.
216 */
217 public final static int ERROR_HTTP_DATA_ERROR = 1004;
218
219 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700220 * Value of {@link #COLUMN_REASON} when there were too many redirects.
Steve Howarda2709362010-07-02 17:12:48 -0700221 */
222 public final static int ERROR_TOO_MANY_REDIRECTS = 1005;
223
224 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700225 * Value of {@link #COLUMN_REASON} when there was insufficient storage space. Typically,
Steve Howarda2709362010-07-02 17:12:48 -0700226 * this is because the SD card is full.
227 */
228 public final static int ERROR_INSUFFICIENT_SPACE = 1006;
229
230 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700231 * Value of {@link #COLUMN_REASON} when no external storage device was found. Typically,
Steve Howarda2709362010-07-02 17:12:48 -0700232 * this is because the SD card is not mounted.
233 */
234 public final static int ERROR_DEVICE_NOT_FOUND = 1007;
235
Steve Howardb8e07a52010-07-21 14:53:21 -0700236 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700237 * Value of {@link #COLUMN_REASON} when some possibly transient error occurred but we can't
Steve Howard33bbd122010-08-02 17:51:29 -0700238 * resume the download.
239 */
240 public final static int ERROR_CANNOT_RESUME = 1008;
241
242 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700243 * Value of {@link #COLUMN_REASON} when the requested destination file already exists (the
Steve Howarda9e87c92010-09-16 12:02:03 -0700244 * download manager will not overwrite an existing file).
245 */
246 public final static int ERROR_FILE_ALREADY_EXISTS = 1009;
247
248 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700249 * Value of {@link #COLUMN_REASON} when the download has failed because of
250 * {@link NetworkPolicyManager} controls on the requesting application.
251 *
252 * @hide
253 */
254 public final static int ERROR_BLOCKED = 1010;
255
256 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700257 * Value of {@link #COLUMN_REASON} when the download is paused because some network error
258 * occurred and the download manager is waiting before retrying the request.
259 */
260 public final static int PAUSED_WAITING_TO_RETRY = 1;
261
262 /**
263 * Value of {@link #COLUMN_REASON} when the download is waiting for network connectivity to
264 * proceed.
265 */
266 public final static int PAUSED_WAITING_FOR_NETWORK = 2;
267
268 /**
269 * Value of {@link #COLUMN_REASON} when the download exceeds a size limit for downloads over
270 * the mobile network and the download manager is waiting for a Wi-Fi connection to proceed.
271 */
272 public final static int PAUSED_QUEUED_FOR_WIFI = 3;
273
274 /**
275 * Value of {@link #COLUMN_REASON} when the download is paused for some other reason.
276 */
277 public final static int PAUSED_UNKNOWN = 4;
278
279 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700280 * Broadcast intent action sent by the download manager when a download completes.
281 */
Jeff Sharkey32cd2fb2013-10-02 10:11:22 -0700282 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Steve Howardb8e07a52010-07-21 14:53:21 -0700283 public final static String ACTION_DOWNLOAD_COMPLETE = "android.intent.action.DOWNLOAD_COMPLETE";
284
285 /**
Steve Howard610c4352010-09-30 18:30:04 -0700286 * Broadcast intent action sent by the download manager when the user clicks on a running
287 * download, either from a system notification or from the downloads UI.
Steve Howardb8e07a52010-07-21 14:53:21 -0700288 */
Jeff Sharkey32cd2fb2013-10-02 10:11:22 -0700289 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Steve Howardb8e07a52010-07-21 14:53:21 -0700290 public final static String ACTION_NOTIFICATION_CLICKED =
291 "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED";
292
293 /**
Steve Howarde78fc182010-09-24 14:59:36 -0700294 * Intent action to launch an activity to display all downloads.
295 */
Jeff Sharkey32cd2fb2013-10-02 10:11:22 -0700296 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
Steve Howarde78fc182010-09-24 14:59:36 -0700297 public final static String ACTION_VIEW_DOWNLOADS = "android.intent.action.VIEW_DOWNLOADS";
298
299 /**
Vasu Norie5f92242011-01-24 16:12:20 -0800300 * Intent extra included with {@link #ACTION_VIEW_DOWNLOADS} to start DownloadApp in
301 * sort-by-size mode.
302 */
303 public final static String INTENT_EXTRAS_SORT_BY_SIZE =
304 "android.app.DownloadManager.extra_sortBySize";
305
306 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700307 * Intent extra included with {@link #ACTION_DOWNLOAD_COMPLETE} intents, indicating the ID (as a
308 * long) of the download that just completed.
309 */
310 public static final String EXTRA_DOWNLOAD_ID = "extra_download_id";
Steve Howarda2709362010-07-02 17:12:48 -0700311
Vasu Nori71b8c232010-10-27 15:22:19 -0700312 /**
313 * When clicks on multiple notifications are received, the following
314 * provides an array of download ids corresponding to the download notification that was
315 * clicked. It can be retrieved by the receiver of this
316 * Intent using {@link android.content.Intent#getLongArrayExtra(String)}.
317 */
318 public static final String EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS = "extra_click_download_ids";
319
Vasu Norie16c43b2010-11-06 18:48:08 -0700320 /**
321 * columns to request from DownloadProvider.
322 * @hide
323 */
324 public static final String[] UNDERLYING_COLUMNS = new String[] {
Steve Howarda2709362010-07-02 17:12:48 -0700325 Downloads.Impl._ID,
Vasu Norie69924f2010-11-15 13:10:11 -0800326 Downloads.Impl._DATA + " AS " + COLUMN_LOCAL_FILENAME,
Vasu Nori216fa222010-10-12 23:08:13 -0700327 Downloads.Impl.COLUMN_MEDIAPROVIDER_URI,
Vasu Nori5be894e2010-11-02 21:55:30 -0700328 Downloads.Impl.COLUMN_DESTINATION,
Vasu Norief7e33b2010-10-20 13:26:02 -0700329 Downloads.Impl.COLUMN_TITLE,
330 Downloads.Impl.COLUMN_DESCRIPTION,
331 Downloads.Impl.COLUMN_URI,
Vasu Norief7e33b2010-10-20 13:26:02 -0700332 Downloads.Impl.COLUMN_STATUS,
Steve Howarda9e87c92010-09-16 12:02:03 -0700333 Downloads.Impl.COLUMN_FILE_NAME_HINT,
Vasu Norie16c43b2010-11-06 18:48:08 -0700334 Downloads.Impl.COLUMN_MIME_TYPE + " AS " + COLUMN_MEDIA_TYPE,
335 Downloads.Impl.COLUMN_TOTAL_BYTES + " AS " + COLUMN_TOTAL_SIZE_BYTES,
336 Downloads.Impl.COLUMN_LAST_MODIFICATION + " AS " + COLUMN_LAST_MODIFIED_TIMESTAMP,
337 Downloads.Impl.COLUMN_CURRENT_BYTES + " AS " + COLUMN_BYTES_DOWNLOADED_SO_FAR,
Jeff Sharkeyb180a652013-09-23 14:23:41 -0700338 Downloads.Impl.COLUMN_ALLOW_WRITE,
Vasu Norie16c43b2010-11-06 18:48:08 -0700339 /* add the following 'computed' columns to the cursor.
340 * they are not 'returned' by the database, but their inclusion
341 * eliminates need to have lot of methods in CursorTranslator
342 */
343 "'placeholder' AS " + COLUMN_LOCAL_URI,
344 "'placeholder' AS " + COLUMN_REASON
Steve Howarda2709362010-07-02 17:12:48 -0700345 };
346
Steve Howarda2709362010-07-02 17:12:48 -0700347 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700348 * This class contains all the information necessary to request a new download. The URI is the
Steve Howarda2709362010-07-02 17:12:48 -0700349 * only required parameter.
Steve Howard4f564cd2010-09-22 15:57:25 -0700350 *
351 * Note that the default download destination is a shared volume where the system might delete
352 * your file if it needs to reclaim space for system use. If this is a problem, use a location
353 * on external storage (see {@link #setDestinationUri(Uri)}.
Steve Howarda2709362010-07-02 17:12:48 -0700354 */
355 public static class Request {
356 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700357 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
358 * {@link ConnectivityManager#TYPE_MOBILE}.
359 */
360 public static final int NETWORK_MOBILE = 1 << 0;
Steve Howarda2709362010-07-02 17:12:48 -0700361
Steve Howardb8e07a52010-07-21 14:53:21 -0700362 /**
363 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
364 * {@link ConnectivityManager#TYPE_WIFI}.
365 */
366 public static final int NETWORK_WIFI = 1 << 1;
367
HÃ¥kan3 Johansson011238b2012-02-08 21:13:35 +0100368 /**
369 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
370 * {@link ConnectivityManager#TYPE_BLUETOOTH}.
371 * @hide
372 */
373 public static final int NETWORK_BLUETOOTH = 1 << 2;
374
Steve Howardb8e07a52010-07-21 14:53:21 -0700375 private Uri mUri;
376 private Uri mDestinationUri;
Steve Howard4f564cd2010-09-22 15:57:25 -0700377 private List<Pair<String, String>> mRequestHeaders = new ArrayList<Pair<String, String>>();
378 private CharSequence mTitle;
379 private CharSequence mDescription;
Steve Howard4f564cd2010-09-22 15:57:25 -0700380 private String mMimeType;
Steve Howardb8e07a52010-07-21 14:53:21 -0700381 private int mAllowedNetworkTypes = ~0; // default to all network types allowed
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700382 private boolean mRoamingAllowed = true;
383 private boolean mMeteredAllowed = true;
Steve Howard90fb15a2010-09-09 16:13:41 -0700384 private boolean mIsVisibleInDownloadsUi = true;
Vasu Nori5be894e2010-11-02 21:55:30 -0700385 private boolean mScannable = false;
Vasu Norif83e6e42010-12-13 16:28:31 -0800386 private boolean mUseSystemCache = false;
Vasu Nori1cde3fb2010-11-05 11:02:52 -0700387 /** if a file is designated as a MediaScanner scannable file, the following value is
388 * stored in the database column {@link Downloads.Impl#COLUMN_MEDIA_SCANNED}.
389 */
390 private static final int SCANNABLE_VALUE_YES = 0;
391 // value of 1 is stored in the above column by DownloadProvider after it is scanned by
392 // MediaScanner
393 /** if a file is designated as a file that should not be scanned by MediaScanner,
394 * the following value is stored in the database column
395 * {@link Downloads.Impl#COLUMN_MEDIA_SCANNED}.
396 */
397 private static final int SCANNABLE_VALUE_NO = 2;
Steve Howarda2709362010-07-02 17:12:48 -0700398
399 /**
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700400 * This download is visible but only shows in the notifications
401 * while it's in progress.
402 */
403 public static final int VISIBILITY_VISIBLE = 0;
404
405 /**
406 * This download is visible and shows in the notifications while
407 * in progress and after completion.
408 */
409 public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED = 1;
410
411 /**
412 * This download doesn't show in the UI or in the notifications.
413 */
414 public static final int VISIBILITY_HIDDEN = 2;
415
Vasu Norif9e85232011-02-10 14:59:54 -0800416 /**
417 * This download shows in the notifications after completion ONLY.
418 * It is usuable only with
Vasu Nori37281302011-03-07 11:25:01 -0800419 * {@link DownloadManager#addCompletedDownload(String, String,
420 * boolean, String, String, long, boolean)}.
Vasu Norif9e85232011-02-10 14:59:54 -0800421 */
422 public static final int VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION = 3;
423
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700424 /** can take any of the following values: {@link #VISIBILITY_HIDDEN}
Vasu Norif9e85232011-02-10 14:59:54 -0800425 * {@link #VISIBILITY_VISIBLE_NOTIFY_COMPLETED}, {@link #VISIBILITY_VISIBLE},
426 * {@link #VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION}
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700427 */
428 private int mNotificationVisibility = VISIBILITY_VISIBLE;
429
430 /**
Alex Klyubin66629bc2015-06-11 14:34:44 -0700431 * @param uri the HTTP or HTTPS URI to download.
Steve Howarda2709362010-07-02 17:12:48 -0700432 */
433 public Request(Uri uri) {
434 if (uri == null) {
435 throw new NullPointerException();
436 }
437 String scheme = uri.getScheme();
Paul Westbrook86a60192010-09-15 12:55:49 -0700438 if (scheme == null || (!scheme.equals("http") && !scheme.equals("https"))) {
439 throw new IllegalArgumentException("Can only download HTTP/HTTPS URIs: " + uri);
Steve Howarda2709362010-07-02 17:12:48 -0700440 }
441 mUri = uri;
442 }
443
Vasu Noric0e50752011-01-20 17:57:54 -0800444 Request(String uriString) {
445 mUri = Uri.parse(uriString);
446 }
447
Steve Howarda2709362010-07-02 17:12:48 -0700448 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700449 * Set the local destination for the downloaded file. Must be a file URI to a path on
Steve Howarda2709362010-07-02 17:12:48 -0700450 * external storage, and the calling application must have the WRITE_EXTERNAL_STORAGE
451 * permission.
Vasu Nori5be894e2010-11-02 21:55:30 -0700452 * <p>
453 * The downloaded file is not scanned by MediaScanner.
454 * But it can be made scannable by calling {@link #allowScanningByMediaScanner()}.
455 * <p>
Steve Howard4f564cd2010-09-22 15:57:25 -0700456 * By default, downloads are saved to a generated filename in the shared download cache and
457 * may be deleted by the system at any time to reclaim space.
Steve Howarda2709362010-07-02 17:12:48 -0700458 *
459 * @return this object
460 */
461 public Request setDestinationUri(Uri uri) {
462 mDestinationUri = uri;
463 return this;
464 }
465
466 /**
Vasu Norif83e6e42010-12-13 16:28:31 -0800467 * Set the local destination for the downloaded file to the system cache dir (/cache).
468 * This is only available to System apps with the permission
469 * {@link android.Manifest.permission#ACCESS_CACHE_FILESYSTEM}.
470 * <p>
471 * The downloaded file is not scanned by MediaScanner.
472 * But it can be made scannable by calling {@link #allowScanningByMediaScanner()}.
473 * <p>
474 * Files downloaded to /cache may be deleted by the system at any time to reclaim space.
475 *
476 * @return this object
477 * @hide
478 */
479 public Request setDestinationToSystemCache() {
480 mUseSystemCache = true;
481 return this;
482 }
483
484 /**
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700485 * Set the local destination for the downloaded file to a path within
486 * the application's external files directory (as returned by
487 * {@link Context#getExternalFilesDir(String)}.
Vasu Nori5be894e2010-11-02 21:55:30 -0700488 * <p>
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700489 * The downloaded file is not scanned by MediaScanner. But it can be
490 * made scannable by calling {@link #allowScanningByMediaScanner()}.
Steve Howard4f564cd2010-09-22 15:57:25 -0700491 *
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700492 * @param context the {@link Context} to use in determining the external
493 * files directory
494 * @param dirType the directory type to pass to
495 * {@link Context#getExternalFilesDir(String)}
496 * @param subPath the path within the external directory, including the
497 * destination filename
Steve Howard4f564cd2010-09-22 15:57:25 -0700498 * @return this object
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700499 * @throws IllegalStateException If the external storage directory
500 * cannot be found or created.
Steve Howard4f564cd2010-09-22 15:57:25 -0700501 */
502 public Request setDestinationInExternalFilesDir(Context context, String dirType,
503 String subPath) {
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700504 final File file = context.getExternalFilesDir(dirType);
505 if (file == null) {
506 throw new IllegalStateException("Failed to get external storage files directory");
507 } else if (file.exists()) {
508 if (!file.isDirectory()) {
509 throw new IllegalStateException(file.getAbsolutePath() +
510 " already exists and is not a directory");
511 }
512 } else {
513 if (!file.mkdirs()) {
514 throw new IllegalStateException("Unable to create directory: "+
515 file.getAbsolutePath());
516 }
517 }
518 setDestinationFromBase(file, subPath);
Steve Howard4f564cd2010-09-22 15:57:25 -0700519 return this;
520 }
521
522 /**
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700523 * Set the local destination for the downloaded file to a path within
524 * the public external storage directory (as returned by
525 * {@link Environment#getExternalStoragePublicDirectory(String)}).
526 * <p>
527 * The downloaded file is not scanned by MediaScanner. But it can be
528 * made scannable by calling {@link #allowScanningByMediaScanner()}.
Steve Howard4f564cd2010-09-22 15:57:25 -0700529 *
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700530 * @param dirType the directory type to pass to {@link Environment#getExternalStoragePublicDirectory(String)}
531 * @param subPath the path within the external directory, including the
532 * destination filename
Steve Howard4f564cd2010-09-22 15:57:25 -0700533 * @return this object
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700534 * @throws IllegalStateException If the external storage directory
535 * cannot be found or created.
Steve Howard4f564cd2010-09-22 15:57:25 -0700536 */
537 public Request setDestinationInExternalPublicDir(String dirType, String subPath) {
Vasu Nori6916b032010-12-19 20:31:00 -0800538 File file = Environment.getExternalStoragePublicDirectory(dirType);
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700539 if (file == null) {
540 throw new IllegalStateException("Failed to get external storage public directory");
541 } else if (file.exists()) {
Vasu Nori6916b032010-12-19 20:31:00 -0800542 if (!file.isDirectory()) {
543 throw new IllegalStateException(file.getAbsolutePath() +
544 " already exists and is not a directory");
545 }
546 } else {
Roger Chen1740ada2012-12-17 13:31:17 +0800547 if (!file.mkdirs()) {
Vasu Nori6916b032010-12-19 20:31:00 -0800548 throw new IllegalStateException("Unable to create directory: "+
549 file.getAbsolutePath());
550 }
551 }
552 setDestinationFromBase(file, subPath);
Steve Howard4f564cd2010-09-22 15:57:25 -0700553 return this;
554 }
555
556 private void setDestinationFromBase(File base, String subPath) {
557 if (subPath == null) {
558 throw new NullPointerException("subPath cannot be null");
559 }
560 mDestinationUri = Uri.withAppendedPath(Uri.fromFile(base), subPath);
561 }
562
563 /**
Vasu Nori5be894e2010-11-02 21:55:30 -0700564 * If the file to be downloaded is to be scanned by MediaScanner, this method
565 * should be called before {@link DownloadManager#enqueue(Request)} is called.
566 */
567 public void allowScanningByMediaScanner() {
568 mScannable = true;
569 }
570
571 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700572 * Add an HTTP header to be included with the download request. The header will be added to
573 * the end of the list.
Steve Howarda2709362010-07-02 17:12:48 -0700574 * @param header HTTP header name
575 * @param value header value
576 * @return this object
Steve Howard4f564cd2010-09-22 15:57:25 -0700577 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2">HTTP/1.1
578 * Message Headers</a>
Steve Howarda2709362010-07-02 17:12:48 -0700579 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700580 public Request addRequestHeader(String header, String value) {
581 if (header == null) {
582 throw new NullPointerException("header cannot be null");
583 }
584 if (header.contains(":")) {
585 throw new IllegalArgumentException("header may not contain ':'");
586 }
587 if (value == null) {
588 value = "";
589 }
590 mRequestHeaders.add(Pair.create(header, value));
Steve Howarda2709362010-07-02 17:12:48 -0700591 return this;
592 }
593
594 /**
Steve Howard610c4352010-09-30 18:30:04 -0700595 * Set the title of this download, to be displayed in notifications (if enabled). If no
596 * title is given, a default one will be assigned based on the download filename, once the
597 * download starts.
Steve Howarda2709362010-07-02 17:12:48 -0700598 * @return this object
599 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700600 public Request setTitle(CharSequence title) {
Steve Howarda2709362010-07-02 17:12:48 -0700601 mTitle = title;
602 return this;
603 }
604
605 /**
606 * Set a description of this download, to be displayed in notifications (if enabled)
607 * @return this object
608 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700609 public Request setDescription(CharSequence description) {
Steve Howarda2709362010-07-02 17:12:48 -0700610 mDescription = description;
611 return this;
612 }
613
614 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700615 * Set the MIME content type of this download. This will override the content type declared
Steve Howarda2709362010-07-02 17:12:48 -0700616 * in the server's response.
Steve Howard4f564cd2010-09-22 15:57:25 -0700617 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7">HTTP/1.1
618 * Media Types</a>
Steve Howarda2709362010-07-02 17:12:48 -0700619 * @return this object
620 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700621 public Request setMimeType(String mimeType) {
622 mMimeType = mimeType;
Steve Howarda2709362010-07-02 17:12:48 -0700623 return this;
624 }
625
626 /**
Steve Howard8e15afe2010-07-28 17:12:40 -0700627 * Control whether a system notification is posted by the download manager while this
628 * download is running. If enabled, the download manager posts notifications about downloads
629 * through the system {@link android.app.NotificationManager}. By default, a notification is
630 * shown.
Steve Howarda2709362010-07-02 17:12:48 -0700631 *
Steve Howard8e15afe2010-07-28 17:12:40 -0700632 * If set to false, this requires the permission
633 * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
634 *
635 * @param show whether the download manager should show a notification for this download.
Steve Howarda2709362010-07-02 17:12:48 -0700636 * @return this object
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700637 * @deprecated use {@link #setNotificationVisibility(int)}
Steve Howarda2709362010-07-02 17:12:48 -0700638 */
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700639 @Deprecated
Steve Howard8e15afe2010-07-28 17:12:40 -0700640 public Request setShowRunningNotification(boolean show) {
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700641 return (show) ? setNotificationVisibility(VISIBILITY_VISIBLE) :
642 setNotificationVisibility(VISIBILITY_HIDDEN);
643 }
644
645 /**
646 * Control whether a system notification is posted by the download manager while this
647 * download is running or when it is completed.
648 * If enabled, the download manager posts notifications about downloads
649 * through the system {@link android.app.NotificationManager}.
650 * By default, a notification is shown only when the download is in progress.
651 *<p>
652 * It can take the following values: {@link #VISIBILITY_HIDDEN},
653 * {@link #VISIBILITY_VISIBLE},
654 * {@link #VISIBILITY_VISIBLE_NOTIFY_COMPLETED}.
655 *<p>
656 * If set to {@link #VISIBILITY_HIDDEN}, this requires the permission
657 * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
658 *
659 * @param visibility the visibility setting value
660 * @return this object
661 */
662 public Request setNotificationVisibility(int visibility) {
663 mNotificationVisibility = visibility;
Steve Howarda2709362010-07-02 17:12:48 -0700664 return this;
665 }
666
Steve Howardb8e07a52010-07-21 14:53:21 -0700667 /**
Jeff Sharkey792e0912012-04-16 11:52:18 -0700668 * Restrict the types of networks over which this download may proceed.
669 * By default, all network types are allowed. Consider using
670 * {@link #setAllowedOverMetered(boolean)} instead, since it's more
671 * flexible.
672 *
Steve Howardb8e07a52010-07-21 14:53:21 -0700673 * @param flags any combination of the NETWORK_* bit flags.
674 * @return this object
675 */
Steve Howarda2709362010-07-02 17:12:48 -0700676 public Request setAllowedNetworkTypes(int flags) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700677 mAllowedNetworkTypes = flags;
678 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700679 }
680
Steve Howardb8e07a52010-07-21 14:53:21 -0700681 /**
682 * Set whether this download may proceed over a roaming connection. By default, roaming is
683 * allowed.
684 * @param allowed whether to allow a roaming connection to be used
685 * @return this object
686 */
Steve Howarda2709362010-07-02 17:12:48 -0700687 public Request setAllowedOverRoaming(boolean allowed) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700688 mRoamingAllowed = allowed;
689 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700690 }
691
692 /**
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700693 * Set whether this download may proceed over a metered network
694 * connection. By default, metered networks are allowed.
695 *
696 * @see ConnectivityManager#isActiveNetworkMetered()
697 */
698 public Request setAllowedOverMetered(boolean allow) {
699 mMeteredAllowed = allow;
700 return this;
701 }
702
703 /**
Steve Howard90fb15a2010-09-09 16:13:41 -0700704 * Set whether this download should be displayed in the system's Downloads UI. True by
705 * default.
706 * @param isVisible whether to display this download in the Downloads UI
707 * @return this object
708 */
709 public Request setVisibleInDownloadsUi(boolean isVisible) {
710 mIsVisibleInDownloadsUi = isVisible;
711 return this;
712 }
713
714 /**
Steve Howarda2709362010-07-02 17:12:48 -0700715 * @return ContentValues to be passed to DownloadProvider.insert()
716 */
Steve Howardb8e07a52010-07-21 14:53:21 -0700717 ContentValues toContentValues(String packageName) {
Steve Howarda2709362010-07-02 17:12:48 -0700718 ContentValues values = new ContentValues();
719 assert mUri != null;
Vasu Norief7e33b2010-10-20 13:26:02 -0700720 values.put(Downloads.Impl.COLUMN_URI, mUri.toString());
Steve Howardb8e07a52010-07-21 14:53:21 -0700721 values.put(Downloads.Impl.COLUMN_IS_PUBLIC_API, true);
Vasu Norief7e33b2010-10-20 13:26:02 -0700722 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE, packageName);
Steve Howarda2709362010-07-02 17:12:48 -0700723
724 if (mDestinationUri != null) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700725 values.put(Downloads.Impl.COLUMN_DESTINATION, Downloads.Impl.DESTINATION_FILE_URI);
726 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, mDestinationUri.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700727 } else {
Vasu Norief7e33b2010-10-20 13:26:02 -0700728 values.put(Downloads.Impl.COLUMN_DESTINATION,
Vasu Norif83e6e42010-12-13 16:28:31 -0800729 (this.mUseSystemCache) ?
730 Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION :
731 Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE);
Steve Howarda2709362010-07-02 17:12:48 -0700732 }
Vasu Nori5be894e2010-11-02 21:55:30 -0700733 // is the file supposed to be media-scannable?
Vasu Nori1cde3fb2010-11-05 11:02:52 -0700734 values.put(Downloads.Impl.COLUMN_MEDIA_SCANNED, (mScannable) ? SCANNABLE_VALUE_YES :
735 SCANNABLE_VALUE_NO);
Steve Howarda2709362010-07-02 17:12:48 -0700736
737 if (!mRequestHeaders.isEmpty()) {
Steve Howardea9147d2010-07-13 19:02:45 -0700738 encodeHttpHeaders(values);
Steve Howarda2709362010-07-02 17:12:48 -0700739 }
740
Vasu Norief7e33b2010-10-20 13:26:02 -0700741 putIfNonNull(values, Downloads.Impl.COLUMN_TITLE, mTitle);
742 putIfNonNull(values, Downloads.Impl.COLUMN_DESCRIPTION, mDescription);
743 putIfNonNull(values, Downloads.Impl.COLUMN_MIME_TYPE, mMimeType);
Steve Howarda2709362010-07-02 17:12:48 -0700744
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700745 values.put(Downloads.Impl.COLUMN_VISIBILITY, mNotificationVisibility);
Steve Howardb8e07a52010-07-21 14:53:21 -0700746 values.put(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES, mAllowedNetworkTypes);
747 values.put(Downloads.Impl.COLUMN_ALLOW_ROAMING, mRoamingAllowed);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700748 values.put(Downloads.Impl.COLUMN_ALLOW_METERED, mMeteredAllowed);
Steve Howard90fb15a2010-09-09 16:13:41 -0700749 values.put(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, mIsVisibleInDownloadsUi);
Steve Howardb8e07a52010-07-21 14:53:21 -0700750
Steve Howarda2709362010-07-02 17:12:48 -0700751 return values;
752 }
753
Steve Howardea9147d2010-07-13 19:02:45 -0700754 private void encodeHttpHeaders(ContentValues values) {
755 int index = 0;
Steve Howard4f564cd2010-09-22 15:57:25 -0700756 for (Pair<String, String> header : mRequestHeaders) {
757 String headerString = header.first + ": " + header.second;
Steve Howardea9147d2010-07-13 19:02:45 -0700758 values.put(Downloads.Impl.RequestHeaders.INSERT_KEY_PREFIX + index, headerString);
759 index++;
760 }
761 }
762
Steve Howard4f564cd2010-09-22 15:57:25 -0700763 private void putIfNonNull(ContentValues contentValues, String key, Object value) {
Steve Howarda2709362010-07-02 17:12:48 -0700764 if (value != null) {
Steve Howard4f564cd2010-09-22 15:57:25 -0700765 contentValues.put(key, value.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700766 }
767 }
768 }
769
770 /**
771 * This class may be used to filter download manager queries.
772 */
773 public static class Query {
Steve Howardf054e192010-09-01 18:26:26 -0700774 /**
775 * Constant for use with {@link #orderBy}
776 * @hide
777 */
778 public static final int ORDER_ASCENDING = 1;
779
780 /**
781 * Constant for use with {@link #orderBy}
782 * @hide
783 */
784 public static final int ORDER_DESCENDING = 2;
785
Steve Howard64c48b82010-10-07 17:53:52 -0700786 private long[] mIds = null;
Steve Howarda2709362010-07-02 17:12:48 -0700787 private Integer mStatusFlags = null;
Vasu Norief7e33b2010-10-20 13:26:02 -0700788 private String mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
Steve Howardf054e192010-09-01 18:26:26 -0700789 private int mOrderDirection = ORDER_DESCENDING;
Steve Howard90fb15a2010-09-09 16:13:41 -0700790 private boolean mOnlyIncludeVisibleInDownloadsUi = false;
Steve Howarda2709362010-07-02 17:12:48 -0700791
792 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700793 * Include only the downloads with the given IDs.
Steve Howarda2709362010-07-02 17:12:48 -0700794 * @return this object
795 */
Steve Howard64c48b82010-10-07 17:53:52 -0700796 public Query setFilterById(long... ids) {
797 mIds = ids;
Steve Howarda2709362010-07-02 17:12:48 -0700798 return this;
799 }
800
801 /**
802 * Include only downloads with status matching any the given status flags.
803 * @param flags any combination of the STATUS_* bit flags
804 * @return this object
805 */
806 public Query setFilterByStatus(int flags) {
807 mStatusFlags = flags;
808 return this;
809 }
810
811 /**
Steve Howard90fb15a2010-09-09 16:13:41 -0700812 * Controls whether this query includes downloads not visible in the system's Downloads UI.
813 * @param value if true, this query will only include downloads that should be displayed in
814 * the system's Downloads UI; if false (the default), this query will include
815 * both visible and invisible downloads.
816 * @return this object
817 * @hide
818 */
819 public Query setOnlyIncludeVisibleInDownloadsUi(boolean value) {
820 mOnlyIncludeVisibleInDownloadsUi = value;
821 return this;
822 }
823
824 /**
Steve Howardf054e192010-09-01 18:26:26 -0700825 * Change the sort order of the returned Cursor.
826 *
827 * @param column one of the COLUMN_* constants; currently, only
828 * {@link #COLUMN_LAST_MODIFIED_TIMESTAMP} and {@link #COLUMN_TOTAL_SIZE_BYTES} are
829 * supported.
830 * @param direction either {@link #ORDER_ASCENDING} or {@link #ORDER_DESCENDING}
831 * @return this object
832 * @hide
833 */
834 public Query orderBy(String column, int direction) {
835 if (direction != ORDER_ASCENDING && direction != ORDER_DESCENDING) {
836 throw new IllegalArgumentException("Invalid direction: " + direction);
837 }
838
839 if (column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP)) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700840 mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
Steve Howardf054e192010-09-01 18:26:26 -0700841 } else if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700842 mOrderByColumn = Downloads.Impl.COLUMN_TOTAL_BYTES;
Steve Howardf054e192010-09-01 18:26:26 -0700843 } else {
844 throw new IllegalArgumentException("Cannot order by " + column);
845 }
846 mOrderDirection = direction;
847 return this;
848 }
849
850 /**
Steve Howarda2709362010-07-02 17:12:48 -0700851 * Run this query using the given ContentResolver.
852 * @param projection the projection to pass to ContentResolver.query()
853 * @return the Cursor returned by ContentResolver.query()
854 */
Steve Howardeca77fc2010-09-12 18:49:08 -0700855 Cursor runQuery(ContentResolver resolver, String[] projection, Uri baseUri) {
856 Uri uri = baseUri;
Steve Howard90fb15a2010-09-09 16:13:41 -0700857 List<String> selectionParts = new ArrayList<String>();
Steve Howard64c48b82010-10-07 17:53:52 -0700858 String[] selectionArgs = null;
Steve Howarda2709362010-07-02 17:12:48 -0700859
Steve Howard64c48b82010-10-07 17:53:52 -0700860 if (mIds != null) {
861 selectionParts.add(getWhereClauseForIds(mIds));
862 selectionArgs = getWhereArgsForIds(mIds);
Steve Howarda2709362010-07-02 17:12:48 -0700863 }
864
865 if (mStatusFlags != null) {
866 List<String> parts = new ArrayList<String>();
867 if ((mStatusFlags & STATUS_PENDING) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700868 parts.add(statusClause("=", Downloads.Impl.STATUS_PENDING));
Steve Howarda2709362010-07-02 17:12:48 -0700869 }
870 if ((mStatusFlags & STATUS_RUNNING) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700871 parts.add(statusClause("=", Downloads.Impl.STATUS_RUNNING));
Steve Howarda2709362010-07-02 17:12:48 -0700872 }
873 if ((mStatusFlags & STATUS_PAUSED) != 0) {
Steve Howard3e8c1d32010-09-29 17:03:32 -0700874 parts.add(statusClause("=", Downloads.Impl.STATUS_PAUSED_BY_APP));
875 parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_TO_RETRY));
876 parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_FOR_NETWORK));
877 parts.add(statusClause("=", Downloads.Impl.STATUS_QUEUED_FOR_WIFI));
Steve Howarda2709362010-07-02 17:12:48 -0700878 }
879 if ((mStatusFlags & STATUS_SUCCESSFUL) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700880 parts.add(statusClause("=", Downloads.Impl.STATUS_SUCCESS));
Steve Howarda2709362010-07-02 17:12:48 -0700881 }
882 if ((mStatusFlags & STATUS_FAILED) != 0) {
883 parts.add("(" + statusClause(">=", 400)
884 + " AND " + statusClause("<", 600) + ")");
885 }
Steve Howard90fb15a2010-09-09 16:13:41 -0700886 selectionParts.add(joinStrings(" OR ", parts));
Steve Howarda2709362010-07-02 17:12:48 -0700887 }
Steve Howardf054e192010-09-01 18:26:26 -0700888
Steve Howard90fb15a2010-09-09 16:13:41 -0700889 if (mOnlyIncludeVisibleInDownloadsUi) {
890 selectionParts.add(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI + " != '0'");
891 }
892
Vasu Nori216fa222010-10-12 23:08:13 -0700893 // only return rows which are not marked 'deleted = 1'
894 selectionParts.add(Downloads.Impl.COLUMN_DELETED + " != '1'");
895
Steve Howard90fb15a2010-09-09 16:13:41 -0700896 String selection = joinStrings(" AND ", selectionParts);
Steve Howardf054e192010-09-01 18:26:26 -0700897 String orderDirection = (mOrderDirection == ORDER_ASCENDING ? "ASC" : "DESC");
898 String orderBy = mOrderByColumn + " " + orderDirection;
899
Steve Howard64c48b82010-10-07 17:53:52 -0700900 return resolver.query(uri, projection, selection, selectionArgs, orderBy);
Steve Howarda2709362010-07-02 17:12:48 -0700901 }
902
903 private String joinStrings(String joiner, Iterable<String> parts) {
904 StringBuilder builder = new StringBuilder();
905 boolean first = true;
906 for (String part : parts) {
907 if (!first) {
908 builder.append(joiner);
909 }
910 builder.append(part);
911 first = false;
912 }
913 return builder.toString();
914 }
915
916 private String statusClause(String operator, int value) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700917 return Downloads.Impl.COLUMN_STATUS + operator + "'" + value + "'";
Steve Howarda2709362010-07-02 17:12:48 -0700918 }
919 }
920
Jeff Sharkey60cfad82016-01-05 17:30:57 -0700921 private final ContentResolver mResolver;
922 private final String mPackageName;
Jeff Sharkey60cfad82016-01-05 17:30:57 -0700923
Steve Howardeca77fc2010-09-12 18:49:08 -0700924 private Uri mBaseUri = Downloads.Impl.CONTENT_URI;
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -0700925 private boolean mAccessFilename;
Steve Howarda2709362010-07-02 17:12:48 -0700926
927 /**
928 * @hide
929 */
Jeff Sharkey60cfad82016-01-05 17:30:57 -0700930 public DownloadManager(Context context) {
931 mResolver = context.getContentResolver();
932 mPackageName = context.getPackageName();
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -0700933
934 // Callers can access filename columns when targeting old platform
935 // versions; otherwise we throw telling them it's deprecated.
936 mAccessFilename = context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N;
Steve Howarda2709362010-07-02 17:12:48 -0700937 }
938
939 /**
Steve Howardeca77fc2010-09-12 18:49:08 -0700940 * Makes this object access the download provider through /all_downloads URIs rather than
941 * /my_downloads URIs, for clients that have permission to do so.
942 * @hide
943 */
944 public void setAccessAllDownloads(boolean accessAllDownloads) {
945 if (accessAllDownloads) {
946 mBaseUri = Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI;
947 } else {
948 mBaseUri = Downloads.Impl.CONTENT_URI;
949 }
950 }
951
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -0700952 /** {@hide} */
953 public void setAccessFilename(boolean accessFilename) {
954 mAccessFilename = accessFilename;
955 }
956
Steve Howardeca77fc2010-09-12 18:49:08 -0700957 /**
Steve Howarda2709362010-07-02 17:12:48 -0700958 * Enqueue a new download. The download will start automatically once the download manager is
959 * ready to execute it and connectivity is available.
960 *
961 * @param request the parameters specifying this download
962 * @return an ID for the download, unique across the system. This ID is used to make future
963 * calls related to this download.
964 */
965 public long enqueue(Request request) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700966 ContentValues values = request.toContentValues(mPackageName);
Vasu Norief7e33b2010-10-20 13:26:02 -0700967 Uri downloadUri = mResolver.insert(Downloads.Impl.CONTENT_URI, values);
Steve Howarda2709362010-07-02 17:12:48 -0700968 long id = Long.parseLong(downloadUri.getLastPathSegment());
969 return id;
970 }
971
972 /**
Vasu Nori216fa222010-10-12 23:08:13 -0700973 * Marks the specified download as 'to be deleted'. This is done when a completed download
974 * is to be removed but the row was stored without enough info to delete the corresponding
975 * metadata from Mediaprovider database. Actual cleanup of this row is done in DownloadService.
976 *
977 * @param ids the IDs of the downloads to be marked 'deleted'
978 * @return the number of downloads actually updated
979 * @hide
980 */
981 public int markRowDeleted(long... ids) {
982 if (ids == null || ids.length == 0) {
983 // called with nothing to remove!
984 throw new IllegalArgumentException("input param 'ids' can't be null");
985 }
986 ContentValues values = new ContentValues();
987 values.put(Downloads.Impl.COLUMN_DELETED, 1);
Vasu Nori8da7a4e2010-11-17 17:14:49 -0800988 // if only one id is passed in, then include it in the uri itself.
989 // this will eliminate a full database scan in the download service.
990 if (ids.length == 1) {
991 return mResolver.update(ContentUris.withAppendedId(mBaseUri, ids[0]), values,
992 null, null);
993 }
Vasu Nori216fa222010-10-12 23:08:13 -0700994 return mResolver.update(mBaseUri, values, getWhereClauseForIds(ids),
995 getWhereArgsForIds(ids));
996 }
997
998 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700999 * Cancel downloads and remove them from the download manager. Each download will be stopped if
Vasu Nori17ee56c2011-02-28 08:35:39 -08001000 * it was running, and it will no longer be accessible through the download manager.
1001 * If there is a downloaded file, partial or complete, it is deleted.
Steve Howarda2709362010-07-02 17:12:48 -07001002 *
Steve Howard64c48b82010-10-07 17:53:52 -07001003 * @param ids the IDs of the downloads to remove
1004 * @return the number of downloads actually removed
Steve Howarda2709362010-07-02 17:12:48 -07001005 */
Steve Howard64c48b82010-10-07 17:53:52 -07001006 public int remove(long... ids) {
Vasu Norie16c43b2010-11-06 18:48:08 -07001007 return markRowDeleted(ids);
Steve Howarda2709362010-07-02 17:12:48 -07001008 }
1009
1010 /**
1011 * Query the download manager about downloads that have been requested.
1012 * @param query parameters specifying filters for this query
1013 * @return a Cursor over the result set of downloads, with columns consisting of all the
1014 * COLUMN_* constants.
1015 */
1016 public Cursor query(Query query) {
Steve Howardeca77fc2010-09-12 18:49:08 -07001017 Cursor underlyingCursor = query.runQuery(mResolver, UNDERLYING_COLUMNS, mBaseUri);
Steve Howardf054e192010-09-01 18:26:26 -07001018 if (underlyingCursor == null) {
1019 return null;
1020 }
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001021 return new CursorTranslator(underlyingCursor, mBaseUri, mAccessFilename);
Steve Howarda2709362010-07-02 17:12:48 -07001022 }
1023
1024 /**
1025 * Open a downloaded file for reading. The download must have completed.
1026 * @param id the ID of the download
1027 * @return a read-only {@link ParcelFileDescriptor}
1028 * @throws FileNotFoundException if the destination file does not already exist
1029 */
1030 public ParcelFileDescriptor openDownloadedFile(long id) throws FileNotFoundException {
1031 return mResolver.openFileDescriptor(getDownloadUri(id), "r");
1032 }
1033
1034 /**
John Spurlock92a262c2013-11-04 16:25:38 -05001035 * Returns the {@link Uri} of the given downloaded file id, if the file is
1036 * downloaded successfully. Otherwise, null is returned.
Vasu Nori5be894e2010-11-02 21:55:30 -07001037 *
1038 * @param id the id of the downloaded file.
Jeff Sharkeyb11683b2015-07-29 10:15:34 -07001039 * @return the {@link Uri} of the given downloaded file id, if download was
1040 * successful. null otherwise.
Vasu Nori5be894e2010-11-02 21:55:30 -07001041 */
1042 public Uri getUriForDownloadedFile(long id) {
1043 // to check if the file is in cache, get its destination from the database
1044 Query query = new Query().setFilterById(id);
1045 Cursor cursor = null;
1046 try {
1047 cursor = query(query);
1048 if (cursor == null) {
1049 return null;
1050 }
Leon Scrogginsd75e64a2010-12-13 15:48:40 -05001051 if (cursor.moveToFirst()) {
Vasu Nori6e2b2a62010-11-16 17:58:22 -08001052 int status = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_STATUS));
Vasu Nori5be894e2010-11-02 21:55:30 -07001053 if (DownloadManager.STATUS_SUCCESSFUL == status) {
Jeff Sharkeyb11683b2015-07-29 10:15:34 -07001054 return ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI, id);
Vasu Nori5be894e2010-11-02 21:55:30 -07001055 }
1056 }
1057 } finally {
1058 if (cursor != null) {
1059 cursor.close();
1060 }
1061 }
1062 // downloaded file not found or its status is not 'successfully completed'
1063 return null;
1064 }
1065
1066 /**
John Spurlock92a262c2013-11-04 16:25:38 -05001067 * Returns the media type of the given downloaded file id, if the file was
1068 * downloaded successfully. Otherwise, null is returned.
Vasu Nori6e2b2a62010-11-16 17:58:22 -08001069 *
1070 * @param id the id of the downloaded file.
John Spurlock92a262c2013-11-04 16:25:38 -05001071 * @return the media type of the given downloaded file id, if download was successful. null
Vasu Nori6e2b2a62010-11-16 17:58:22 -08001072 * otherwise.
1073 */
1074 public String getMimeTypeForDownloadedFile(long id) {
1075 Query query = new Query().setFilterById(id);
1076 Cursor cursor = null;
1077 try {
1078 cursor = query(query);
1079 if (cursor == null) {
1080 return null;
1081 }
1082 while (cursor.moveToFirst()) {
1083 return cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_MEDIA_TYPE));
1084 }
1085 } finally {
1086 if (cursor != null) {
1087 cursor.close();
1088 }
1089 }
1090 // downloaded file not found or its status is not 'successfully completed'
1091 return null;
1092 }
1093
1094 /**
Steve Howard64c48b82010-10-07 17:53:52 -07001095 * Restart the given downloads, which must have already completed (successfully or not). This
Steve Howard90fb15a2010-09-09 16:13:41 -07001096 * method will only work when called from within the download manager's process.
Steve Howard64c48b82010-10-07 17:53:52 -07001097 * @param ids the IDs of the downloads
Steve Howard90fb15a2010-09-09 16:13:41 -07001098 * @hide
1099 */
Steve Howard64c48b82010-10-07 17:53:52 -07001100 public void restartDownload(long... ids) {
1101 Cursor cursor = query(new Query().setFilterById(ids));
Steve Howard90fb15a2010-09-09 16:13:41 -07001102 try {
Steve Howard64c48b82010-10-07 17:53:52 -07001103 for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
1104 int status = cursor.getInt(cursor.getColumnIndex(COLUMN_STATUS));
1105 if (status != STATUS_SUCCESSFUL && status != STATUS_FAILED) {
1106 throw new IllegalArgumentException("Cannot restart incomplete download: "
1107 + cursor.getLong(cursor.getColumnIndex(COLUMN_ID)));
1108 }
Steve Howard90fb15a2010-09-09 16:13:41 -07001109 }
1110 } finally {
1111 cursor.close();
1112 }
1113
1114 ContentValues values = new ContentValues();
1115 values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, 0);
1116 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, -1);
1117 values.putNull(Downloads.Impl._DATA);
1118 values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING);
Jeff Sharkey54781202013-01-17 17:27:33 -08001119 values.put(Downloads.Impl.COLUMN_FAILED_CONNECTIONS, 0);
Steve Howard64c48b82010-10-07 17:53:52 -07001120 mResolver.update(mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
Steve Howard90fb15a2010-09-09 16:13:41 -07001121 }
1122
1123 /**
Vasu Nori0abbf802011-01-17 15:08:14 -08001124 * Returns maximum size, in bytes, of downloads that may go over a mobile connection; or null if
1125 * there's no limit
1126 *
1127 * @param context the {@link Context} to use for accessing the {@link ContentResolver}
1128 * @return maximum size, in bytes, of downloads that may go over a mobile connection; or null if
1129 * there's no limit
1130 */
1131 public static Long getMaxBytesOverMobile(Context context) {
1132 try {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001133 return Settings.Global.getLong(context.getContentResolver(),
1134 Settings.Global.DOWNLOAD_MAX_BYTES_OVER_MOBILE);
Vasu Nori0abbf802011-01-17 15:08:14 -08001135 } catch (SettingNotFoundException exc) {
1136 return null;
1137 }
1138 }
1139
1140 /**
1141 * Returns recommended maximum size, in bytes, of downloads that may go over a mobile
1142 * connection; or null if there's no recommended limit. The user will have the option to bypass
1143 * this limit.
1144 *
1145 * @param context the {@link Context} to use for accessing the {@link ContentResolver}
1146 * @return recommended maximum size, in bytes, of downloads that may go over a mobile
1147 * connection; or null if there's no recommended limit.
1148 */
1149 public static Long getRecommendedMaxBytesOverMobile(Context context) {
1150 try {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001151 return Settings.Global.getLong(context.getContentResolver(),
1152 Settings.Global.DOWNLOAD_RECOMMENDED_MAX_BYTES_OVER_MOBILE);
Vasu Nori0abbf802011-01-17 15:08:14 -08001153 } catch (SettingNotFoundException exc) {
1154 return null;
1155 }
1156 }
Vasu Noric0e50752011-01-20 17:57:54 -08001157
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001158 /** {@hide} */
1159 public static boolean isActiveNetworkExpensive(Context context) {
1160 // TODO: connect to NetworkPolicyManager
1161 return false;
1162 }
1163
1164 /** {@hide} */
1165 public static long getActiveNetworkWarningBytes(Context context) {
1166 // TODO: connect to NetworkPolicyManager
1167 return -1;
1168 }
1169
Vasu Noric0e50752011-01-20 17:57:54 -08001170 /**
1171 * Adds a file to the downloads database system, so it could appear in Downloads App
1172 * (and thus become eligible for management by the Downloads App).
1173 * <p>
1174 * It is helpful to make the file scannable by MediaScanner by setting the param
1175 * isMediaScannerScannable to true. It makes the file visible in media managing
1176 * applications such as Gallery App, which could be a useful purpose of using this API.
1177 *
1178 * @param title the title that would appear for this file in Downloads App.
1179 * @param description the description that would appear for this file in Downloads App.
1180 * @param isMediaScannerScannable true if the file is to be scanned by MediaScanner. Files
1181 * scanned by MediaScanner appear in the applications used to view media (for example,
1182 * Gallery app).
1183 * @param mimeType mimetype of the file.
1184 * @param path absolute pathname to the file. The file should be world-readable, so that it can
1185 * be managed by the Downloads App and any other app that is used to read it (for example,
1186 * Gallery app to display the file, if the file contents represent a video/image).
1187 * @param length length of the downloaded file
Vasu Norif9e85232011-02-10 14:59:54 -08001188 * @param showNotification true if a notification is to be sent, false otherwise
Vasu Noric0e50752011-01-20 17:57:54 -08001189 * @return an ID for the download entry added to the downloads app, unique across the system
1190 * This ID is used to make future calls related to this download.
1191 */
Vasu Nori37281302011-03-07 11:25:01 -08001192 public long addCompletedDownload(String title, String description,
Vasu Norif9e85232011-02-10 14:59:54 -08001193 boolean isMediaScannerScannable, String mimeType, String path, long length,
1194 boolean showNotification) {
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001195 return addCompletedDownload(title, description, isMediaScannerScannable, mimeType, path,
Edward Cunningham735a31e2016-02-05 00:44:45 -08001196 length, showNotification, false, null, null);
1197 }
1198
1199 /**
1200 * Adds a file to the downloads database system, so it could appear in Downloads App
1201 * (and thus become eligible for management by the Downloads App).
1202 * <p>
1203 * It is helpful to make the file scannable by MediaScanner by setting the param
1204 * isMediaScannerScannable to true. It makes the file visible in media managing
1205 * applications such as Gallery App, which could be a useful purpose of using this API.
1206 *
1207 * @param title the title that would appear for this file in Downloads App.
1208 * @param description the description that would appear for this file in Downloads App.
1209 * @param isMediaScannerScannable true if the file is to be scanned by MediaScanner. Files
1210 * scanned by MediaScanner appear in the applications used to view media (for example,
1211 * Gallery app).
1212 * @param mimeType mimetype of the file.
1213 * @param path absolute pathname to the file. The file should be world-readable, so that it can
1214 * be managed by the Downloads App and any other app that is used to read it (for example,
1215 * Gallery app to display the file, if the file contents represent a video/image).
1216 * @param length length of the downloaded file
1217 * @param showNotification true if a notification is to be sent, false otherwise
1218 * @param uri the original HTTP URI of the download
1219 * @param referer the HTTP Referer for the download
1220 * @return an ID for the download entry added to the downloads app, unique across the system
1221 * This ID is used to make future calls related to this download.
1222 */
1223 public long addCompletedDownload(String title, String description,
1224 boolean isMediaScannerScannable, String mimeType, String path, long length,
1225 boolean showNotification, Uri uri, Uri referer) {
1226 return addCompletedDownload(title, description, isMediaScannerScannable, mimeType, path,
1227 length, showNotification, false, uri, referer);
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001228 }
1229
1230 /** {@hide} */
1231 public long addCompletedDownload(String title, String description,
1232 boolean isMediaScannerScannable, String mimeType, String path, long length,
1233 boolean showNotification, boolean allowWrite) {
Edward Cunningham735a31e2016-02-05 00:44:45 -08001234 return addCompletedDownload(title, description, isMediaScannerScannable, mimeType, path,
1235 length, showNotification, allowWrite, null, null);
1236 }
1237
1238 /** {@hide} */
1239 public long addCompletedDownload(String title, String description,
1240 boolean isMediaScannerScannable, String mimeType, String path, long length,
1241 boolean showNotification, boolean allowWrite, Uri uri, Uri referer) {
Vasu Noric0e50752011-01-20 17:57:54 -08001242 // make sure the input args are non-null/non-zero
1243 validateArgumentIsNonEmpty("title", title);
1244 validateArgumentIsNonEmpty("description", description);
1245 validateArgumentIsNonEmpty("path", path);
1246 validateArgumentIsNonEmpty("mimeType", mimeType);
Jeff Sharkey33f95ed2012-05-02 17:07:54 -07001247 if (length < 0) {
Vasu Noric0e50752011-01-20 17:57:54 -08001248 throw new IllegalArgumentException(" invalid value for param: totalBytes");
1249 }
1250
1251 // if there is already an entry with the given path name in downloads.db, return its id
Edward Cunningham735a31e2016-02-05 00:44:45 -08001252 Request request;
1253 if (uri != null) {
1254 request = new Request(uri);
1255 } else {
1256 request = new Request(NON_DOWNLOADMANAGER_DOWNLOAD);
1257 }
1258 request.setTitle(title)
Vasu Noric0e50752011-01-20 17:57:54 -08001259 .setDescription(description)
1260 .setMimeType(mimeType);
Edward Cunningham735a31e2016-02-05 00:44:45 -08001261 if (referer != null) {
1262 request.addRequestHeader("Referer", referer.toString());
1263 }
Vasu Noric0e50752011-01-20 17:57:54 -08001264 ContentValues values = request.toContentValues(null);
1265 values.put(Downloads.Impl.COLUMN_DESTINATION,
1266 Downloads.Impl.DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD);
1267 values.put(Downloads.Impl._DATA, path);
1268 values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_SUCCESS);
1269 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, length);
1270 values.put(Downloads.Impl.COLUMN_MEDIA_SCANNED,
1271 (isMediaScannerScannable) ? Request.SCANNABLE_VALUE_YES :
1272 Request.SCANNABLE_VALUE_NO);
Vasu Norif9e85232011-02-10 14:59:54 -08001273 values.put(Downloads.Impl.COLUMN_VISIBILITY, (showNotification) ?
1274 Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION : Request.VISIBILITY_HIDDEN);
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001275 values.put(Downloads.Impl.COLUMN_ALLOW_WRITE, allowWrite ? 1 : 0);
Vasu Noric0e50752011-01-20 17:57:54 -08001276 Uri downloadUri = mResolver.insert(Downloads.Impl.CONTENT_URI, values);
1277 if (downloadUri == null) {
1278 return -1;
1279 }
1280 return Long.parseLong(downloadUri.getLastPathSegment());
1281 }
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001282
Vasu Noric0e50752011-01-20 17:57:54 -08001283 private static final String NON_DOWNLOADMANAGER_DOWNLOAD =
1284 "non-dwnldmngr-download-dont-retry2download";
1285
1286 private static void validateArgumentIsNonEmpty(String paramName, String val) {
1287 if (TextUtils.isEmpty(val)) {
1288 throw new IllegalArgumentException(paramName + " can't be null");
1289 }
1290 }
1291
Vasu Nori0abbf802011-01-17 15:08:14 -08001292 /**
Steve Howarda2709362010-07-02 17:12:48 -07001293 * Get the DownloadProvider URI for the download with the given ID.
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001294 *
1295 * @hide
Steve Howarda2709362010-07-02 17:12:48 -07001296 */
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001297 public Uri getDownloadUri(long id) {
Steve Howardeca77fc2010-09-12 18:49:08 -07001298 return ContentUris.withAppendedId(mBaseUri, id);
Steve Howarda2709362010-07-02 17:12:48 -07001299 }
1300
1301 /**
Steve Howard64c48b82010-10-07 17:53:52 -07001302 * Get a parameterized SQL WHERE clause to select a bunch of IDs.
1303 */
1304 static String getWhereClauseForIds(long[] ids) {
1305 StringBuilder whereClause = new StringBuilder();
Vasu Norie7be6bd2010-10-10 14:58:08 -07001306 whereClause.append("(");
Steve Howard64c48b82010-10-07 17:53:52 -07001307 for (int i = 0; i < ids.length; i++) {
1308 if (i > 0) {
Vasu Norie7be6bd2010-10-10 14:58:08 -07001309 whereClause.append("OR ");
Steve Howard64c48b82010-10-07 17:53:52 -07001310 }
Vasu Norie7be6bd2010-10-10 14:58:08 -07001311 whereClause.append(Downloads.Impl._ID);
1312 whereClause.append(" = ? ");
Steve Howard64c48b82010-10-07 17:53:52 -07001313 }
1314 whereClause.append(")");
1315 return whereClause.toString();
1316 }
1317
1318 /**
1319 * Get the selection args for a clause returned by {@link #getWhereClauseForIds(long[])}.
1320 */
1321 static String[] getWhereArgsForIds(long[] ids) {
1322 String[] whereArgs = new String[ids.length];
1323 for (int i = 0; i < ids.length; i++) {
1324 whereArgs[i] = Long.toString(ids[i]);
1325 }
1326 return whereArgs;
1327 }
1328
1329 /**
Steve Howarda2709362010-07-02 17:12:48 -07001330 * This class wraps a cursor returned by DownloadProvider -- the "underlying cursor" -- and
1331 * presents a different set of columns, those defined in the DownloadManager.COLUMN_* constants.
1332 * Some columns correspond directly to underlying values while others are computed from
1333 * underlying data.
1334 */
1335 private static class CursorTranslator extends CursorWrapper {
Jeff Sharkey60cfad82016-01-05 17:30:57 -07001336 private final Uri mBaseUri;
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001337 private final boolean mAccessFilename;
Steve Howardeca77fc2010-09-12 18:49:08 -07001338
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001339 public CursorTranslator(Cursor cursor, Uri baseUri, boolean accessFilename) {
Steve Howarda2709362010-07-02 17:12:48 -07001340 super(cursor);
Steve Howardeca77fc2010-09-12 18:49:08 -07001341 mBaseUri = baseUri;
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001342 mAccessFilename = accessFilename;
Steve Howarda2709362010-07-02 17:12:48 -07001343 }
1344
1345 @Override
Steve Howarda2709362010-07-02 17:12:48 -07001346 public int getInt(int columnIndex) {
1347 return (int) getLong(columnIndex);
1348 }
1349
1350 @Override
1351 public long getLong(int columnIndex) {
Vasu Norie16c43b2010-11-06 18:48:08 -07001352 if (getColumnName(columnIndex).equals(COLUMN_REASON)) {
1353 return getReason(super.getInt(getColumnIndex(Downloads.Impl.COLUMN_STATUS)));
1354 } else if (getColumnName(columnIndex).equals(COLUMN_STATUS)) {
1355 return translateStatus(super.getInt(getColumnIndex(Downloads.Impl.COLUMN_STATUS)));
1356 } else {
1357 return super.getLong(columnIndex);
1358 }
Steve Howarda2709362010-07-02 17:12:48 -07001359 }
1360
1361 @Override
1362 public String getString(int columnIndex) {
Jeff Sharkey60cfad82016-01-05 17:30:57 -07001363 final String columnName = getColumnName(columnIndex);
1364 switch (columnName) {
1365 case COLUMN_LOCAL_URI:
1366 return getLocalUri();
1367 case COLUMN_LOCAL_FILENAME:
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001368 if (!mAccessFilename) {
Jeff Sharkey60cfad82016-01-05 17:30:57 -07001369 throw new IllegalArgumentException(
1370 "COLUMN_LOCAL_FILENAME is deprecated;"
1371 + " use ContentResolver.openFileDescriptor() instead");
1372 }
1373 default:
1374 return super.getString(columnIndex);
1375 }
Steve Howardeca77fc2010-09-12 18:49:08 -07001376 }
1377
1378 private String getLocalUri() {
Vasu Norie16c43b2010-11-06 18:48:08 -07001379 long destinationType = getLong(getColumnIndex(Downloads.Impl.COLUMN_DESTINATION));
1380 if (destinationType == Downloads.Impl.DESTINATION_FILE_URI ||
Vasu Noric0e50752011-01-20 17:57:54 -08001381 destinationType == Downloads.Impl.DESTINATION_EXTERNAL ||
1382 destinationType == Downloads.Impl.DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD) {
Vasu Nori98f03072010-11-15 17:22:20 -08001383 String localPath = getString(getColumnIndex(COLUMN_LOCAL_FILENAME));
Steve Howard99047d72010-09-29 17:41:37 -07001384 if (localPath == null) {
1385 return null;
1386 }
1387 return Uri.fromFile(new File(localPath)).toString();
Steve Howardbb0d23b2010-09-22 18:56:29 -07001388 }
1389
Steve Howardeca77fc2010-09-12 18:49:08 -07001390 // return content URI for cache download
Vasu Norie16c43b2010-11-06 18:48:08 -07001391 long downloadId = getLong(getColumnIndex(Downloads.Impl._ID));
Steve Howardeca77fc2010-09-12 18:49:08 -07001392 return ContentUris.withAppendedId(mBaseUri, downloadId).toString();
Steve Howarda2709362010-07-02 17:12:48 -07001393 }
1394
Steve Howard3e8c1d32010-09-29 17:03:32 -07001395 private long getReason(int status) {
1396 switch (translateStatus(status)) {
1397 case STATUS_FAILED:
1398 return getErrorCode(status);
1399
1400 case STATUS_PAUSED:
1401 return getPausedReason(status);
1402
1403 default:
1404 return 0; // arbitrary value when status is not an error
Steve Howarda2709362010-07-02 17:12:48 -07001405 }
Steve Howard3e8c1d32010-09-29 17:03:32 -07001406 }
1407
1408 private long getPausedReason(int status) {
1409 switch (status) {
1410 case Downloads.Impl.STATUS_WAITING_TO_RETRY:
1411 return PAUSED_WAITING_TO_RETRY;
1412
1413 case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
1414 return PAUSED_WAITING_FOR_NETWORK;
1415
1416 case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
1417 return PAUSED_QUEUED_FOR_WIFI;
1418
1419 default:
1420 return PAUSED_UNKNOWN;
1421 }
1422 }
1423
1424 private long getErrorCode(int status) {
Steve Howard33bbd122010-08-02 17:51:29 -07001425 if ((400 <= status && status < Downloads.Impl.MIN_ARTIFICIAL_ERROR_STATUS)
1426 || (500 <= status && status < 600)) {
Steve Howarda2709362010-07-02 17:12:48 -07001427 // HTTP status code
1428 return status;
1429 }
1430
1431 switch (status) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001432 case Downloads.Impl.STATUS_FILE_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001433 return ERROR_FILE_ERROR;
1434
Vasu Norief7e33b2010-10-20 13:26:02 -07001435 case Downloads.Impl.STATUS_UNHANDLED_HTTP_CODE:
1436 case Downloads.Impl.STATUS_UNHANDLED_REDIRECT:
Steve Howarda2709362010-07-02 17:12:48 -07001437 return ERROR_UNHANDLED_HTTP_CODE;
1438
Vasu Norief7e33b2010-10-20 13:26:02 -07001439 case Downloads.Impl.STATUS_HTTP_DATA_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001440 return ERROR_HTTP_DATA_ERROR;
1441
Vasu Norief7e33b2010-10-20 13:26:02 -07001442 case Downloads.Impl.STATUS_TOO_MANY_REDIRECTS:
Steve Howarda2709362010-07-02 17:12:48 -07001443 return ERROR_TOO_MANY_REDIRECTS;
1444
Vasu Norief7e33b2010-10-20 13:26:02 -07001445 case Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001446 return ERROR_INSUFFICIENT_SPACE;
1447
Vasu Norief7e33b2010-10-20 13:26:02 -07001448 case Downloads.Impl.STATUS_DEVICE_NOT_FOUND_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001449 return ERROR_DEVICE_NOT_FOUND;
1450
Steve Howard33bbd122010-08-02 17:51:29 -07001451 case Downloads.Impl.STATUS_CANNOT_RESUME:
1452 return ERROR_CANNOT_RESUME;
1453
Steve Howarda9e87c92010-09-16 12:02:03 -07001454 case Downloads.Impl.STATUS_FILE_ALREADY_EXISTS_ERROR:
1455 return ERROR_FILE_ALREADY_EXISTS;
1456
Steve Howarda2709362010-07-02 17:12:48 -07001457 default:
1458 return ERROR_UNKNOWN;
1459 }
1460 }
1461
Steve Howard3e8c1d32010-09-29 17:03:32 -07001462 private int translateStatus(int status) {
Steve Howarda2709362010-07-02 17:12:48 -07001463 switch (status) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001464 case Downloads.Impl.STATUS_PENDING:
Steve Howarda2709362010-07-02 17:12:48 -07001465 return STATUS_PENDING;
1466
Vasu Norief7e33b2010-10-20 13:26:02 -07001467 case Downloads.Impl.STATUS_RUNNING:
Steve Howarda2709362010-07-02 17:12:48 -07001468 return STATUS_RUNNING;
1469
Steve Howard3e8c1d32010-09-29 17:03:32 -07001470 case Downloads.Impl.STATUS_PAUSED_BY_APP:
1471 case Downloads.Impl.STATUS_WAITING_TO_RETRY:
1472 case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
1473 case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
Steve Howarda2709362010-07-02 17:12:48 -07001474 return STATUS_PAUSED;
1475
Vasu Norief7e33b2010-10-20 13:26:02 -07001476 case Downloads.Impl.STATUS_SUCCESS:
Steve Howarda2709362010-07-02 17:12:48 -07001477 return STATUS_SUCCESSFUL;
1478
1479 default:
Vasu Norief7e33b2010-10-20 13:26:02 -07001480 assert Downloads.Impl.isStatusError(status);
Steve Howarda2709362010-07-02 17:12:48 -07001481 return STATUS_FAILED;
1482 }
1483 }
1484 }
1485}