blob: fde1d29eb709c6f0bc04f49c56e1faa9d2734463 [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
Ben Lin726bf6a2016-04-27 11:38:05 -070019import android.annotation.Nullable;
Jeff Sharkey32cd2fb2013-10-02 10:11:22 -070020import android.annotation.SdkConstant;
Jeff Sharkey4233f032017-07-15 12:58:38 -060021import android.annotation.SdkConstant.SdkConstantType;
Jeff Sharkey8d5d0652017-04-04 14:38:39 -060022import android.annotation.SystemApi;
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060023import android.annotation.SystemService;
Mathew Inwood61e8ae62018-08-14 14:17:44 +010024import android.annotation.UnsupportedAppUsage;
Steve Howarda2709362010-07-02 17:12:48 -070025import android.content.ContentResolver;
Steve Howardeca77fc2010-09-12 18:49:08 -070026import android.content.ContentUris;
Steve Howarda2709362010-07-02 17:12:48 -070027import android.content.ContentValues;
Steve Howard4f564cd2010-09-22 15:57:25 -070028import android.content.Context;
Steve Howarda2709362010-07-02 17:12:48 -070029import android.database.Cursor;
30import android.database.CursorWrapper;
Steve Howardd58429f2010-09-27 16:32:39 -070031import android.net.ConnectivityManager;
Jeff Sharkey1a303952011-06-16 13:04:20 -070032import android.net.NetworkPolicyManager;
Steve Howardd58429f2010-09-27 16:32:39 -070033import android.net.Uri;
Jeff Sharkey60cfad82016-01-05 17:30:57 -070034import android.os.Build;
Steve Howard4f564cd2010-09-22 15:57:25 -070035import android.os.Environment;
Ben Lin726bf6a2016-04-27 11:38:05 -070036import android.os.FileUtils;
Steve Howarda2709362010-07-02 17:12:48 -070037import android.os.ParcelFileDescriptor;
38import android.provider.Downloads;
Jeff Sharkey4233f032017-07-15 12:58:38 -060039import android.provider.Settings;
Vasu Nori0abbf802011-01-17 15:08:14 -080040import android.provider.Settings.SettingNotFoundException;
Vasu Noric0e50752011-01-20 17:57:54 -080041import android.text.TextUtils;
Steve Howard4f564cd2010-09-22 15:57:25 -070042import android.util.Pair;
Steve Howarda2709362010-07-02 17:12:48 -070043
Steve Howard4f564cd2010-09-22 15:57:25 -070044import java.io.File;
Steve Howarda2709362010-07-02 17:12:48 -070045import java.io.FileNotFoundException;
46import java.util.ArrayList;
Steve Howarda2709362010-07-02 17:12:48 -070047import java.util.List;
Steve Howarda2709362010-07-02 17:12:48 -070048
49/**
50 * The download manager is a system service that handles long-running HTTP downloads. Clients may
51 * request that a URI be downloaded to a particular destination file. The download manager will
52 * conduct the download in the background, taking care of HTTP interactions and retrying downloads
53 * after failures or across connectivity changes and system reboots.
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060054 * <p>
Steve Howard610c4352010-09-30 18:30:04 -070055 * Apps that request downloads through this API should register a broadcast receiver for
56 * {@link #ACTION_NOTIFICATION_CLICKED} to appropriately handle when the user clicks on a running
57 * download in a notification or from the downloads UI.
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060058 * <p>
Nicolas Falliere9530e3a2012-06-18 17:21:06 -070059 * Note that the application must have the {@link android.Manifest.permission#INTERNET}
60 * permission to use this class.
Steve Howarda2709362010-07-02 17:12:48 -070061 */
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060062@SystemService(Context.DOWNLOAD_SERVICE)
Steve Howarda2709362010-07-02 17:12:48 -070063public class DownloadManager {
Vasu Norie7be6bd2010-10-10 14:58:08 -070064
Steve Howarda2709362010-07-02 17:12:48 -070065 /**
66 * An identifier for a particular download, unique across the system. Clients use this ID to
67 * make subsequent calls related to the download.
68 */
Vasu Norief7e33b2010-10-20 13:26:02 -070069 public final static String COLUMN_ID = Downloads.Impl._ID;
Steve Howarda2709362010-07-02 17:12:48 -070070
71 /**
Steve Howard8651bd52010-08-03 12:35:32 -070072 * The client-supplied title for this download. This will be displayed in system notifications.
73 * Defaults to the empty string.
Steve Howarda2709362010-07-02 17:12:48 -070074 */
Vasu Norief7e33b2010-10-20 13:26:02 -070075 public final static String COLUMN_TITLE = Downloads.Impl.COLUMN_TITLE;
Steve Howarda2709362010-07-02 17:12:48 -070076
77 /**
78 * The client-supplied description of this download. This will be displayed in system
Steve Howard8651bd52010-08-03 12:35:32 -070079 * notifications. Defaults to the empty string.
Steve Howarda2709362010-07-02 17:12:48 -070080 */
Vasu Norief7e33b2010-10-20 13:26:02 -070081 public final static String COLUMN_DESCRIPTION = Downloads.Impl.COLUMN_DESCRIPTION;
Steve Howarda2709362010-07-02 17:12:48 -070082
83 /**
84 * URI to be downloaded.
85 */
Vasu Norief7e33b2010-10-20 13:26:02 -070086 public final static String COLUMN_URI = Downloads.Impl.COLUMN_URI;
Steve Howarda2709362010-07-02 17:12:48 -070087
88 /**
Steve Howard8651bd52010-08-03 12:35:32 -070089 * Internet Media Type of the downloaded file. If no value is provided upon creation, this will
90 * initially be null and will be filled in based on the server's response once the download has
91 * started.
Steve Howarda2709362010-07-02 17:12:48 -070092 *
93 * @see <a href="http://www.ietf.org/rfc/rfc1590.txt">RFC 1590, defining Media Types</a>
94 */
95 public final static String COLUMN_MEDIA_TYPE = "media_type";
96
97 /**
Steve Howard8651bd52010-08-03 12:35:32 -070098 * Total size of the download in bytes. This will initially be -1 and will be filled in once
99 * the download starts.
Steve Howarda2709362010-07-02 17:12:48 -0700100 */
101 public final static String COLUMN_TOTAL_SIZE_BYTES = "total_size";
102
103 /**
104 * Uri where downloaded file will be stored. If a destination is supplied by client, that URI
Steve Howard8651bd52010-08-03 12:35:32 -0700105 * will be used here. Otherwise, the value will initially be null and will be filled in with a
106 * generated URI once the download has started.
Steve Howarda2709362010-07-02 17:12:48 -0700107 */
108 public final static String COLUMN_LOCAL_URI = "local_uri";
109
110 /**
Jeff Sharkey60cfad82016-01-05 17:30:57 -0700111 * Path to the downloaded file on disk.
112 * <p>
113 * Note that apps may not have filesystem permissions to directly access
114 * this path. Instead of trying to open this path directly, apps should use
115 * {@link ContentResolver#openFileDescriptor(Uri, String)} to gain access.
116 *
117 * @deprecated apps should transition to using
118 * {@link ContentResolver#openFileDescriptor(Uri, String)}
119 * instead.
Doug Zongkeree04af32010-10-08 13:42:16 -0700120 */
Jeff Sharkey60cfad82016-01-05 17:30:57 -0700121 @Deprecated
Doug Zongkeree04af32010-10-08 13:42:16 -0700122 public final static String COLUMN_LOCAL_FILENAME = "local_filename";
123
124 /**
Steve Howarda2709362010-07-02 17:12:48 -0700125 * Current status of the download, as one of the STATUS_* constants.
126 */
Vasu Norief7e33b2010-10-20 13:26:02 -0700127 public final static String COLUMN_STATUS = Downloads.Impl.COLUMN_STATUS;
Steve Howarda2709362010-07-02 17:12:48 -0700128
129 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700130 * Provides more detail on the status of the download. Its meaning depends on the value of
131 * {@link #COLUMN_STATUS}.
Steve Howarda2709362010-07-02 17:12:48 -0700132 *
Steve Howard3e8c1d32010-09-29 17:03:32 -0700133 * When {@link #COLUMN_STATUS} is {@link #STATUS_FAILED}, this indicates the type of error that
134 * occurred. If an HTTP error occurred, this will hold the HTTP status code as defined in RFC
135 * 2616. Otherwise, it will hold one of the ERROR_* constants.
136 *
137 * When {@link #COLUMN_STATUS} is {@link #STATUS_PAUSED}, this indicates why the download is
138 * paused. It will hold one of the PAUSED_* constants.
139 *
140 * If {@link #COLUMN_STATUS} is neither {@link #STATUS_FAILED} nor {@link #STATUS_PAUSED}, this
141 * column's value is undefined.
Steve Howarda2709362010-07-02 17:12:48 -0700142 *
143 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1.1">RFC 2616
144 * status codes</a>
145 */
Steve Howard3e8c1d32010-09-29 17:03:32 -0700146 public final static String COLUMN_REASON = "reason";
Steve Howarda2709362010-07-02 17:12:48 -0700147
148 /**
149 * Number of bytes download so far.
150 */
151 public final static String COLUMN_BYTES_DOWNLOADED_SO_FAR = "bytes_so_far";
152
153 /**
Steve Howardadcb6972010-07-12 17:09:25 -0700154 * Timestamp when the download was last modified, in {@link System#currentTimeMillis
Steve Howarda2709362010-07-02 17:12:48 -0700155 * System.currentTimeMillis()} (wall clock time in UTC).
156 */
Steve Howardadcb6972010-07-12 17:09:25 -0700157 public final static String COLUMN_LAST_MODIFIED_TIMESTAMP = "last_modified_timestamp";
Steve Howarda2709362010-07-02 17:12:48 -0700158
Vasu Nori216fa222010-10-12 23:08:13 -0700159 /**
160 * The URI to the corresponding entry in MediaProvider for this downloaded entry. It is
161 * used to delete the entries from MediaProvider database when it is deleted from the
162 * downloaded list.
163 */
Vasu Norief7e33b2010-10-20 13:26:02 -0700164 public static final String COLUMN_MEDIAPROVIDER_URI = Downloads.Impl.COLUMN_MEDIAPROVIDER_URI;
Steve Howarda2709362010-07-02 17:12:48 -0700165
166 /**
Jeff Sharkeyb180a652013-09-23 14:23:41 -0700167 * @hide
168 */
169 public final static String COLUMN_ALLOW_WRITE = Downloads.Impl.COLUMN_ALLOW_WRITE;
170
171 /**
Steve Howarda2709362010-07-02 17:12:48 -0700172 * Value of {@link #COLUMN_STATUS} when the download is waiting to start.
173 */
174 public final static int STATUS_PENDING = 1 << 0;
175
176 /**
177 * Value of {@link #COLUMN_STATUS} when the download is currently running.
178 */
179 public final static int STATUS_RUNNING = 1 << 1;
180
181 /**
182 * Value of {@link #COLUMN_STATUS} when the download is waiting to retry or resume.
183 */
184 public final static int STATUS_PAUSED = 1 << 2;
185
186 /**
187 * Value of {@link #COLUMN_STATUS} when the download has successfully completed.
188 */
189 public final static int STATUS_SUCCESSFUL = 1 << 3;
190
191 /**
192 * Value of {@link #COLUMN_STATUS} when the download has failed (and will not be retried).
193 */
194 public final static int STATUS_FAILED = 1 << 4;
195
Steve Howarda2709362010-07-02 17:12:48 -0700196 /**
197 * Value of COLUMN_ERROR_CODE when the download has completed with an error that doesn't fit
198 * under any other error code.
199 */
200 public final static int ERROR_UNKNOWN = 1000;
201
202 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700203 * Value of {@link #COLUMN_REASON} when a storage issue arises which doesn't fit under any
Steve Howarda2709362010-07-02 17:12:48 -0700204 * other error code. Use the more specific {@link #ERROR_INSUFFICIENT_SPACE} and
205 * {@link #ERROR_DEVICE_NOT_FOUND} when appropriate.
206 */
207 public final static int ERROR_FILE_ERROR = 1001;
208
209 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700210 * Value of {@link #COLUMN_REASON} when an HTTP code was received that download manager
Steve Howarda2709362010-07-02 17:12:48 -0700211 * can't handle.
212 */
213 public final static int ERROR_UNHANDLED_HTTP_CODE = 1002;
214
215 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700216 * Value of {@link #COLUMN_REASON} when an error receiving or processing data occurred at
Steve Howarda2709362010-07-02 17:12:48 -0700217 * the HTTP level.
218 */
219 public final static int ERROR_HTTP_DATA_ERROR = 1004;
220
221 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700222 * Value of {@link #COLUMN_REASON} when there were too many redirects.
Steve Howarda2709362010-07-02 17:12:48 -0700223 */
224 public final static int ERROR_TOO_MANY_REDIRECTS = 1005;
225
226 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700227 * Value of {@link #COLUMN_REASON} when there was insufficient storage space. Typically,
Steve Howarda2709362010-07-02 17:12:48 -0700228 * this is because the SD card is full.
229 */
230 public final static int ERROR_INSUFFICIENT_SPACE = 1006;
231
232 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700233 * Value of {@link #COLUMN_REASON} when no external storage device was found. Typically,
Steve Howarda2709362010-07-02 17:12:48 -0700234 * this is because the SD card is not mounted.
235 */
236 public final static int ERROR_DEVICE_NOT_FOUND = 1007;
237
Steve Howardb8e07a52010-07-21 14:53:21 -0700238 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700239 * Value of {@link #COLUMN_REASON} when some possibly transient error occurred but we can't
Steve Howard33bbd122010-08-02 17:51:29 -0700240 * resume the download.
241 */
242 public final static int ERROR_CANNOT_RESUME = 1008;
243
244 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700245 * Value of {@link #COLUMN_REASON} when the requested destination file already exists (the
Steve Howarda9e87c92010-09-16 12:02:03 -0700246 * download manager will not overwrite an existing file).
247 */
248 public final static int ERROR_FILE_ALREADY_EXISTS = 1009;
249
250 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700251 * Value of {@link #COLUMN_REASON} when the download has failed because of
252 * {@link NetworkPolicyManager} controls on the requesting application.
253 *
254 * @hide
255 */
256 public final static int ERROR_BLOCKED = 1010;
257
258 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700259 * Value of {@link #COLUMN_REASON} when the download is paused because some network error
260 * occurred and the download manager is waiting before retrying the request.
261 */
262 public final static int PAUSED_WAITING_TO_RETRY = 1;
263
264 /**
265 * Value of {@link #COLUMN_REASON} when the download is waiting for network connectivity to
266 * proceed.
267 */
268 public final static int PAUSED_WAITING_FOR_NETWORK = 2;
269
270 /**
271 * Value of {@link #COLUMN_REASON} when the download exceeds a size limit for downloads over
272 * the mobile network and the download manager is waiting for a Wi-Fi connection to proceed.
273 */
274 public final static int PAUSED_QUEUED_FOR_WIFI = 3;
275
276 /**
277 * Value of {@link #COLUMN_REASON} when the download is paused for some other reason.
278 */
279 public final static int PAUSED_UNKNOWN = 4;
280
281 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700282 * Broadcast intent action sent by the download manager when a download completes.
283 */
Jeff Sharkey32cd2fb2013-10-02 10:11:22 -0700284 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Steve Howardb8e07a52010-07-21 14:53:21 -0700285 public final static String ACTION_DOWNLOAD_COMPLETE = "android.intent.action.DOWNLOAD_COMPLETE";
286
287 /**
Steve Howard610c4352010-09-30 18:30:04 -0700288 * Broadcast intent action sent by the download manager when the user clicks on a running
289 * download, either from a system notification or from the downloads UI.
Steve Howardb8e07a52010-07-21 14:53:21 -0700290 */
Jeff Sharkey32cd2fb2013-10-02 10:11:22 -0700291 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Steve Howardb8e07a52010-07-21 14:53:21 -0700292 public final static String ACTION_NOTIFICATION_CLICKED =
293 "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED";
294
295 /**
Steve Howarde78fc182010-09-24 14:59:36 -0700296 * Intent action to launch an activity to display all downloads.
297 */
Jeff Sharkey32cd2fb2013-10-02 10:11:22 -0700298 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
Steve Howarde78fc182010-09-24 14:59:36 -0700299 public final static String ACTION_VIEW_DOWNLOADS = "android.intent.action.VIEW_DOWNLOADS";
300
301 /**
Vasu Norie5f92242011-01-24 16:12:20 -0800302 * Intent extra included with {@link #ACTION_VIEW_DOWNLOADS} to start DownloadApp in
303 * sort-by-size mode.
304 */
305 public final static String INTENT_EXTRAS_SORT_BY_SIZE =
306 "android.app.DownloadManager.extra_sortBySize";
307
308 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700309 * Intent extra included with {@link #ACTION_DOWNLOAD_COMPLETE} intents, indicating the ID (as a
310 * long) of the download that just completed.
311 */
312 public static final String EXTRA_DOWNLOAD_ID = "extra_download_id";
Steve Howarda2709362010-07-02 17:12:48 -0700313
Vasu Nori71b8c232010-10-27 15:22:19 -0700314 /**
315 * When clicks on multiple notifications are received, the following
316 * provides an array of download ids corresponding to the download notification that was
317 * clicked. It can be retrieved by the receiver of this
318 * Intent using {@link android.content.Intent#getLongArrayExtra(String)}.
319 */
320 public static final String EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS = "extra_click_download_ids";
321
Jeff Sharkey8d5d0652017-04-04 14:38:39 -0600322 /** {@hide} */
323 @SystemApi
324 public static final String ACTION_DOWNLOAD_COMPLETED =
325 "android.intent.action.DOWNLOAD_COMPLETED";
326
Vasu Norie16c43b2010-11-06 18:48:08 -0700327 /**
328 * columns to request from DownloadProvider.
329 * @hide
330 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100331 @UnsupportedAppUsage
Vasu Norie16c43b2010-11-06 18:48:08 -0700332 public static final String[] UNDERLYING_COLUMNS = new String[] {
Steve Howarda2709362010-07-02 17:12:48 -0700333 Downloads.Impl._ID,
Vasu Norie69924f2010-11-15 13:10:11 -0800334 Downloads.Impl._DATA + " AS " + COLUMN_LOCAL_FILENAME,
Vasu Nori216fa222010-10-12 23:08:13 -0700335 Downloads.Impl.COLUMN_MEDIAPROVIDER_URI,
Vasu Nori5be894e2010-11-02 21:55:30 -0700336 Downloads.Impl.COLUMN_DESTINATION,
Vasu Norief7e33b2010-10-20 13:26:02 -0700337 Downloads.Impl.COLUMN_TITLE,
338 Downloads.Impl.COLUMN_DESCRIPTION,
339 Downloads.Impl.COLUMN_URI,
Vasu Norief7e33b2010-10-20 13:26:02 -0700340 Downloads.Impl.COLUMN_STATUS,
Steve Howarda9e87c92010-09-16 12:02:03 -0700341 Downloads.Impl.COLUMN_FILE_NAME_HINT,
Vasu Norie16c43b2010-11-06 18:48:08 -0700342 Downloads.Impl.COLUMN_MIME_TYPE + " AS " + COLUMN_MEDIA_TYPE,
343 Downloads.Impl.COLUMN_TOTAL_BYTES + " AS " + COLUMN_TOTAL_SIZE_BYTES,
344 Downloads.Impl.COLUMN_LAST_MODIFICATION + " AS " + COLUMN_LAST_MODIFIED_TIMESTAMP,
345 Downloads.Impl.COLUMN_CURRENT_BYTES + " AS " + COLUMN_BYTES_DOWNLOADED_SO_FAR,
Jeff Sharkeyb180a652013-09-23 14:23:41 -0700346 Downloads.Impl.COLUMN_ALLOW_WRITE,
Vasu Norie16c43b2010-11-06 18:48:08 -0700347 /* add the following 'computed' columns to the cursor.
348 * they are not 'returned' by the database, but their inclusion
349 * eliminates need to have lot of methods in CursorTranslator
350 */
351 "'placeholder' AS " + COLUMN_LOCAL_URI,
352 "'placeholder' AS " + COLUMN_REASON
Steve Howarda2709362010-07-02 17:12:48 -0700353 };
354
Steve Howarda2709362010-07-02 17:12:48 -0700355 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700356 * This class contains all the information necessary to request a new download. The URI is the
Steve Howarda2709362010-07-02 17:12:48 -0700357 * only required parameter.
Steve Howard4f564cd2010-09-22 15:57:25 -0700358 *
359 * Note that the default download destination is a shared volume where the system might delete
360 * your file if it needs to reclaim space for system use. If this is a problem, use a location
361 * on external storage (see {@link #setDestinationUri(Uri)}.
Steve Howarda2709362010-07-02 17:12:48 -0700362 */
363 public static class Request {
364 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700365 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
366 * {@link ConnectivityManager#TYPE_MOBILE}.
367 */
368 public static final int NETWORK_MOBILE = 1 << 0;
Steve Howarda2709362010-07-02 17:12:48 -0700369
Steve Howardb8e07a52010-07-21 14:53:21 -0700370 /**
371 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
372 * {@link ConnectivityManager#TYPE_WIFI}.
373 */
374 public static final int NETWORK_WIFI = 1 << 1;
375
HÃ¥kan3 Johansson011238b2012-02-08 21:13:35 +0100376 /**
377 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
378 * {@link ConnectivityManager#TYPE_BLUETOOTH}.
379 * @hide
380 */
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600381 @Deprecated
HÃ¥kan3 Johansson011238b2012-02-08 21:13:35 +0100382 public static final int NETWORK_BLUETOOTH = 1 << 2;
383
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100384 @UnsupportedAppUsage
Steve Howardb8e07a52010-07-21 14:53:21 -0700385 private Uri mUri;
386 private Uri mDestinationUri;
Steve Howard4f564cd2010-09-22 15:57:25 -0700387 private List<Pair<String, String>> mRequestHeaders = new ArrayList<Pair<String, String>>();
388 private CharSequence mTitle;
389 private CharSequence mDescription;
Steve Howard4f564cd2010-09-22 15:57:25 -0700390 private String mMimeType;
Steve Howardb8e07a52010-07-21 14:53:21 -0700391 private int mAllowedNetworkTypes = ~0; // default to all network types allowed
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700392 private boolean mRoamingAllowed = true;
393 private boolean mMeteredAllowed = true;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600394 private int mFlags = 0;
Steve Howard90fb15a2010-09-09 16:13:41 -0700395 private boolean mIsVisibleInDownloadsUi = true;
Vasu Nori5be894e2010-11-02 21:55:30 -0700396 private boolean mScannable = false;
Vasu Nori1cde3fb2010-11-05 11:02:52 -0700397 /** if a file is designated as a MediaScanner scannable file, the following value is
398 * stored in the database column {@link Downloads.Impl#COLUMN_MEDIA_SCANNED}.
399 */
Sudheer Shanka684c02a2019-01-29 17:41:15 -0800400 private static final int SCANNABLE_VALUE_YES = Downloads.Impl.MEDIA_NOT_SCANNED;
Vasu Nori1cde3fb2010-11-05 11:02:52 -0700401 // value of 1 is stored in the above column by DownloadProvider after it is scanned by
402 // MediaScanner
403 /** if a file is designated as a file that should not be scanned by MediaScanner,
404 * the following value is stored in the database column
405 * {@link Downloads.Impl#COLUMN_MEDIA_SCANNED}.
406 */
Sudheer Shanka684c02a2019-01-29 17:41:15 -0800407 private static final int SCANNABLE_VALUE_NO = Downloads.Impl.MEDIA_NOT_SCANNABLE;
Steve Howarda2709362010-07-02 17:12:48 -0700408
409 /**
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700410 * This download is visible but only shows in the notifications
411 * while it's in progress.
412 */
413 public static final int VISIBILITY_VISIBLE = 0;
414
415 /**
416 * This download is visible and shows in the notifications while
417 * in progress and after completion.
418 */
419 public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED = 1;
420
421 /**
422 * This download doesn't show in the UI or in the notifications.
423 */
424 public static final int VISIBILITY_HIDDEN = 2;
425
Vasu Norif9e85232011-02-10 14:59:54 -0800426 /**
427 * This download shows in the notifications after completion ONLY.
428 * It is usuable only with
Vasu Nori37281302011-03-07 11:25:01 -0800429 * {@link DownloadManager#addCompletedDownload(String, String,
430 * boolean, String, String, long, boolean)}.
Vasu Norif9e85232011-02-10 14:59:54 -0800431 */
432 public static final int VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION = 3;
433
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700434 /** can take any of the following values: {@link #VISIBILITY_HIDDEN}
Vasu Norif9e85232011-02-10 14:59:54 -0800435 * {@link #VISIBILITY_VISIBLE_NOTIFY_COMPLETED}, {@link #VISIBILITY_VISIBLE},
436 * {@link #VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION}
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700437 */
438 private int mNotificationVisibility = VISIBILITY_VISIBLE;
439
440 /**
Alex Klyubin66629bc2015-06-11 14:34:44 -0700441 * @param uri the HTTP or HTTPS URI to download.
Steve Howarda2709362010-07-02 17:12:48 -0700442 */
443 public Request(Uri uri) {
444 if (uri == null) {
445 throw new NullPointerException();
446 }
447 String scheme = uri.getScheme();
Paul Westbrook86a60192010-09-15 12:55:49 -0700448 if (scheme == null || (!scheme.equals("http") && !scheme.equals("https"))) {
449 throw new IllegalArgumentException("Can only download HTTP/HTTPS URIs: " + uri);
Steve Howarda2709362010-07-02 17:12:48 -0700450 }
451 mUri = uri;
452 }
453
Vasu Noric0e50752011-01-20 17:57:54 -0800454 Request(String uriString) {
455 mUri = Uri.parse(uriString);
456 }
457
Steve Howarda2709362010-07-02 17:12:48 -0700458 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700459 * Set the local destination for the downloaded file. Must be a file URI to a path on
Steve Howarda2709362010-07-02 17:12:48 -0700460 * external storage, and the calling application must have the WRITE_EXTERNAL_STORAGE
461 * permission.
Vasu Nori5be894e2010-11-02 21:55:30 -0700462 * <p>
463 * The downloaded file is not scanned by MediaScanner.
464 * But it can be made scannable by calling {@link #allowScanningByMediaScanner()}.
465 * <p>
Steve Howard4f564cd2010-09-22 15:57:25 -0700466 * By default, downloads are saved to a generated filename in the shared download cache and
467 * may be deleted by the system at any time to reclaim space.
Steve Howarda2709362010-07-02 17:12:48 -0700468 *
469 * @return this object
470 */
471 public Request setDestinationUri(Uri uri) {
472 mDestinationUri = uri;
473 return this;
474 }
475
476 /**
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700477 * Set the local destination for the downloaded file to a path within
478 * the application's external files directory (as returned by
479 * {@link Context#getExternalFilesDir(String)}.
Vasu Nori5be894e2010-11-02 21:55:30 -0700480 * <p>
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700481 * The downloaded file is not scanned by MediaScanner. But it can be
482 * made scannable by calling {@link #allowScanningByMediaScanner()}.
Steve Howard4f564cd2010-09-22 15:57:25 -0700483 *
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700484 * @param context the {@link Context} to use in determining the external
485 * files directory
486 * @param dirType the directory type to pass to
487 * {@link Context#getExternalFilesDir(String)}
488 * @param subPath the path within the external directory, including the
489 * destination filename
Steve Howard4f564cd2010-09-22 15:57:25 -0700490 * @return this object
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700491 * @throws IllegalStateException If the external storage directory
492 * cannot be found or created.
Steve Howard4f564cd2010-09-22 15:57:25 -0700493 */
494 public Request setDestinationInExternalFilesDir(Context context, String dirType,
495 String subPath) {
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700496 final File file = context.getExternalFilesDir(dirType);
497 if (file == null) {
498 throw new IllegalStateException("Failed to get external storage files directory");
499 } else if (file.exists()) {
500 if (!file.isDirectory()) {
501 throw new IllegalStateException(file.getAbsolutePath() +
502 " already exists and is not a directory");
503 }
504 } else {
505 if (!file.mkdirs()) {
506 throw new IllegalStateException("Unable to create directory: "+
507 file.getAbsolutePath());
508 }
509 }
510 setDestinationFromBase(file, subPath);
Steve Howard4f564cd2010-09-22 15:57:25 -0700511 return this;
512 }
513
514 /**
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700515 * Set the local destination for the downloaded file to a path within
516 * the public external storage directory (as returned by
517 * {@link Environment#getExternalStoragePublicDirectory(String)}).
518 * <p>
519 * The downloaded file is not scanned by MediaScanner. But it can be
520 * made scannable by calling {@link #allowScanningByMediaScanner()}.
Steve Howard4f564cd2010-09-22 15:57:25 -0700521 *
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700522 * @param dirType the directory type to pass to {@link Environment#getExternalStoragePublicDirectory(String)}
523 * @param subPath the path within the external directory, including the
524 * destination filename
Steve Howard4f564cd2010-09-22 15:57:25 -0700525 * @return this object
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700526 * @throws IllegalStateException If the external storage directory
527 * cannot be found or created.
Steve Howard4f564cd2010-09-22 15:57:25 -0700528 */
529 public Request setDestinationInExternalPublicDir(String dirType, String subPath) {
Vasu Nori6916b032010-12-19 20:31:00 -0800530 File file = Environment.getExternalStoragePublicDirectory(dirType);
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700531 if (file == null) {
532 throw new IllegalStateException("Failed to get external storage public directory");
533 } else if (file.exists()) {
Vasu Nori6916b032010-12-19 20:31:00 -0800534 if (!file.isDirectory()) {
535 throw new IllegalStateException(file.getAbsolutePath() +
536 " already exists and is not a directory");
537 }
538 } else {
Roger Chen1740ada2012-12-17 13:31:17 +0800539 if (!file.mkdirs()) {
Vasu Nori6916b032010-12-19 20:31:00 -0800540 throw new IllegalStateException("Unable to create directory: "+
541 file.getAbsolutePath());
542 }
543 }
544 setDestinationFromBase(file, subPath);
Steve Howard4f564cd2010-09-22 15:57:25 -0700545 return this;
546 }
547
548 private void setDestinationFromBase(File base, String subPath) {
549 if (subPath == null) {
550 throw new NullPointerException("subPath cannot be null");
551 }
552 mDestinationUri = Uri.withAppendedPath(Uri.fromFile(base), subPath);
553 }
554
555 /**
Vasu Nori5be894e2010-11-02 21:55:30 -0700556 * If the file to be downloaded is to be scanned by MediaScanner, this method
557 * should be called before {@link DownloadManager#enqueue(Request)} is called.
558 */
559 public void allowScanningByMediaScanner() {
560 mScannable = true;
561 }
562
563 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700564 * Add an HTTP header to be included with the download request. The header will be added to
565 * the end of the list.
Steve Howarda2709362010-07-02 17:12:48 -0700566 * @param header HTTP header name
567 * @param value header value
568 * @return this object
Steve Howard4f564cd2010-09-22 15:57:25 -0700569 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2">HTTP/1.1
570 * Message Headers</a>
Steve Howarda2709362010-07-02 17:12:48 -0700571 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700572 public Request addRequestHeader(String header, String value) {
573 if (header == null) {
574 throw new NullPointerException("header cannot be null");
575 }
576 if (header.contains(":")) {
577 throw new IllegalArgumentException("header may not contain ':'");
578 }
579 if (value == null) {
580 value = "";
581 }
582 mRequestHeaders.add(Pair.create(header, value));
Steve Howarda2709362010-07-02 17:12:48 -0700583 return this;
584 }
585
586 /**
Steve Howard610c4352010-09-30 18:30:04 -0700587 * Set the title of this download, to be displayed in notifications (if enabled). If no
588 * title is given, a default one will be assigned based on the download filename, once the
589 * download starts.
Steve Howarda2709362010-07-02 17:12:48 -0700590 * @return this object
591 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700592 public Request setTitle(CharSequence title) {
Steve Howarda2709362010-07-02 17:12:48 -0700593 mTitle = title;
594 return this;
595 }
596
597 /**
598 * Set a description of this download, to be displayed in notifications (if enabled)
599 * @return this object
600 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700601 public Request setDescription(CharSequence description) {
Steve Howarda2709362010-07-02 17:12:48 -0700602 mDescription = description;
603 return this;
604 }
605
606 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700607 * Set the MIME content type of this download. This will override the content type declared
Steve Howarda2709362010-07-02 17:12:48 -0700608 * in the server's response.
Steve Howard4f564cd2010-09-22 15:57:25 -0700609 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7">HTTP/1.1
610 * Media Types</a>
Steve Howarda2709362010-07-02 17:12:48 -0700611 * @return this object
612 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700613 public Request setMimeType(String mimeType) {
614 mMimeType = mimeType;
Steve Howarda2709362010-07-02 17:12:48 -0700615 return this;
616 }
617
618 /**
Steve Howard8e15afe2010-07-28 17:12:40 -0700619 * Control whether a system notification is posted by the download manager while this
620 * download is running. If enabled, the download manager posts notifications about downloads
621 * through the system {@link android.app.NotificationManager}. By default, a notification is
622 * shown.
Steve Howarda2709362010-07-02 17:12:48 -0700623 *
Steve Howard8e15afe2010-07-28 17:12:40 -0700624 * If set to false, this requires the permission
625 * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
626 *
627 * @param show whether the download manager should show a notification for this download.
Steve Howarda2709362010-07-02 17:12:48 -0700628 * @return this object
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700629 * @deprecated use {@link #setNotificationVisibility(int)}
Steve Howarda2709362010-07-02 17:12:48 -0700630 */
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700631 @Deprecated
Steve Howard8e15afe2010-07-28 17:12:40 -0700632 public Request setShowRunningNotification(boolean show) {
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700633 return (show) ? setNotificationVisibility(VISIBILITY_VISIBLE) :
634 setNotificationVisibility(VISIBILITY_HIDDEN);
635 }
636
637 /**
638 * Control whether a system notification is posted by the download manager while this
639 * download is running or when it is completed.
640 * If enabled, the download manager posts notifications about downloads
641 * through the system {@link android.app.NotificationManager}.
642 * By default, a notification is shown only when the download is in progress.
643 *<p>
644 * It can take the following values: {@link #VISIBILITY_HIDDEN},
645 * {@link #VISIBILITY_VISIBLE},
646 * {@link #VISIBILITY_VISIBLE_NOTIFY_COMPLETED}.
647 *<p>
648 * If set to {@link #VISIBILITY_HIDDEN}, this requires the permission
649 * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
650 *
651 * @param visibility the visibility setting value
652 * @return this object
653 */
654 public Request setNotificationVisibility(int visibility) {
655 mNotificationVisibility = visibility;
Steve Howarda2709362010-07-02 17:12:48 -0700656 return this;
657 }
658
Steve Howardb8e07a52010-07-21 14:53:21 -0700659 /**
Jeff Sharkey792e0912012-04-16 11:52:18 -0700660 * Restrict the types of networks over which this download may proceed.
661 * By default, all network types are allowed. Consider using
662 * {@link #setAllowedOverMetered(boolean)} instead, since it's more
663 * flexible.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600664 * <p>
665 * As of {@link android.os.Build.VERSION_CODES#N}, setting only the
666 * {@link #NETWORK_WIFI} flag here is equivalent to calling
667 * {@link #setAllowedOverMetered(boolean)} with {@code false}.
Jeff Sharkey792e0912012-04-16 11:52:18 -0700668 *
Steve Howardb8e07a52010-07-21 14:53:21 -0700669 * @param flags any combination of the NETWORK_* bit flags.
670 * @return this object
671 */
Steve Howarda2709362010-07-02 17:12:48 -0700672 public Request setAllowedNetworkTypes(int flags) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700673 mAllowedNetworkTypes = flags;
674 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700675 }
676
Steve Howardb8e07a52010-07-21 14:53:21 -0700677 /**
678 * Set whether this download may proceed over a roaming connection. By default, roaming is
679 * allowed.
680 * @param allowed whether to allow a roaming connection to be used
681 * @return this object
682 */
Steve Howarda2709362010-07-02 17:12:48 -0700683 public Request setAllowedOverRoaming(boolean allowed) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700684 mRoamingAllowed = allowed;
685 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700686 }
687
688 /**
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700689 * Set whether this download may proceed over a metered network
690 * connection. By default, metered networks are allowed.
691 *
692 * @see ConnectivityManager#isActiveNetworkMetered()
693 */
694 public Request setAllowedOverMetered(boolean allow) {
695 mMeteredAllowed = allow;
696 return this;
697 }
698
699 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600700 * Specify that to run this download, the device needs to be plugged in.
701 * This defaults to false.
702 *
703 * @param requiresCharging Whether or not the device is plugged in.
704 * @see android.app.job.JobInfo.Builder#setRequiresCharging(boolean)
705 */
706 public Request setRequiresCharging(boolean requiresCharging) {
707 if (requiresCharging) {
708 mFlags |= Downloads.Impl.FLAG_REQUIRES_CHARGING;
709 } else {
710 mFlags &= ~Downloads.Impl.FLAG_REQUIRES_CHARGING;
711 }
712 return this;
713 }
714
715 /**
716 * Specify that to run, the download needs the device to be in idle
717 * mode. This defaults to false.
718 * <p>
719 * Idle mode is a loose definition provided by the system, which means
720 * that the device is not in use, and has not been in use for some time.
721 *
722 * @param requiresDeviceIdle Whether or not the device need be within an
723 * idle maintenance window.
724 * @see android.app.job.JobInfo.Builder#setRequiresDeviceIdle(boolean)
725 */
726 public Request setRequiresDeviceIdle(boolean requiresDeviceIdle) {
727 if (requiresDeviceIdle) {
728 mFlags |= Downloads.Impl.FLAG_REQUIRES_DEVICE_IDLE;
729 } else {
730 mFlags &= ~Downloads.Impl.FLAG_REQUIRES_DEVICE_IDLE;
731 }
732 return this;
733 }
734
735 /**
Steve Howard90fb15a2010-09-09 16:13:41 -0700736 * Set whether this download should be displayed in the system's Downloads UI. True by
737 * default.
738 * @param isVisible whether to display this download in the Downloads UI
739 * @return this object
740 */
741 public Request setVisibleInDownloadsUi(boolean isVisible) {
742 mIsVisibleInDownloadsUi = isVisible;
743 return this;
744 }
745
746 /**
Steve Howarda2709362010-07-02 17:12:48 -0700747 * @return ContentValues to be passed to DownloadProvider.insert()
748 */
Steve Howardb8e07a52010-07-21 14:53:21 -0700749 ContentValues toContentValues(String packageName) {
Steve Howarda2709362010-07-02 17:12:48 -0700750 ContentValues values = new ContentValues();
751 assert mUri != null;
Vasu Norief7e33b2010-10-20 13:26:02 -0700752 values.put(Downloads.Impl.COLUMN_URI, mUri.toString());
Steve Howardb8e07a52010-07-21 14:53:21 -0700753 values.put(Downloads.Impl.COLUMN_IS_PUBLIC_API, true);
Vasu Norief7e33b2010-10-20 13:26:02 -0700754 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE, packageName);
Steve Howarda2709362010-07-02 17:12:48 -0700755
756 if (mDestinationUri != null) {
Jeff Sharkey4233f032017-07-15 12:58:38 -0600757 values.put(Downloads.Impl.COLUMN_DESTINATION,
758 Downloads.Impl.DESTINATION_FILE_URI);
759 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT,
760 mDestinationUri.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700761 } else {
Vasu Norief7e33b2010-10-20 13:26:02 -0700762 values.put(Downloads.Impl.COLUMN_DESTINATION,
Jeff Sharkey4233f032017-07-15 12:58:38 -0600763 Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE);
Steve Howarda2709362010-07-02 17:12:48 -0700764 }
Vasu Nori5be894e2010-11-02 21:55:30 -0700765 // is the file supposed to be media-scannable?
Vasu Nori1cde3fb2010-11-05 11:02:52 -0700766 values.put(Downloads.Impl.COLUMN_MEDIA_SCANNED, (mScannable) ? SCANNABLE_VALUE_YES :
767 SCANNABLE_VALUE_NO);
Steve Howarda2709362010-07-02 17:12:48 -0700768
769 if (!mRequestHeaders.isEmpty()) {
Steve Howardea9147d2010-07-13 19:02:45 -0700770 encodeHttpHeaders(values);
Steve Howarda2709362010-07-02 17:12:48 -0700771 }
772
Vasu Norief7e33b2010-10-20 13:26:02 -0700773 putIfNonNull(values, Downloads.Impl.COLUMN_TITLE, mTitle);
774 putIfNonNull(values, Downloads.Impl.COLUMN_DESCRIPTION, mDescription);
775 putIfNonNull(values, Downloads.Impl.COLUMN_MIME_TYPE, mMimeType);
Steve Howarda2709362010-07-02 17:12:48 -0700776
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700777 values.put(Downloads.Impl.COLUMN_VISIBILITY, mNotificationVisibility);
Steve Howardb8e07a52010-07-21 14:53:21 -0700778 values.put(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES, mAllowedNetworkTypes);
779 values.put(Downloads.Impl.COLUMN_ALLOW_ROAMING, mRoamingAllowed);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700780 values.put(Downloads.Impl.COLUMN_ALLOW_METERED, mMeteredAllowed);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600781 values.put(Downloads.Impl.COLUMN_FLAGS, mFlags);
Steve Howard90fb15a2010-09-09 16:13:41 -0700782 values.put(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, mIsVisibleInDownloadsUi);
Steve Howardb8e07a52010-07-21 14:53:21 -0700783
Steve Howarda2709362010-07-02 17:12:48 -0700784 return values;
785 }
786
Steve Howardea9147d2010-07-13 19:02:45 -0700787 private void encodeHttpHeaders(ContentValues values) {
788 int index = 0;
Steve Howard4f564cd2010-09-22 15:57:25 -0700789 for (Pair<String, String> header : mRequestHeaders) {
790 String headerString = header.first + ": " + header.second;
Steve Howardea9147d2010-07-13 19:02:45 -0700791 values.put(Downloads.Impl.RequestHeaders.INSERT_KEY_PREFIX + index, headerString);
792 index++;
793 }
794 }
795
Steve Howard4f564cd2010-09-22 15:57:25 -0700796 private void putIfNonNull(ContentValues contentValues, String key, Object value) {
Steve Howarda2709362010-07-02 17:12:48 -0700797 if (value != null) {
Steve Howard4f564cd2010-09-22 15:57:25 -0700798 contentValues.put(key, value.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700799 }
800 }
801 }
802
803 /**
804 * This class may be used to filter download manager queries.
805 */
806 public static class Query {
Steve Howardf054e192010-09-01 18:26:26 -0700807 /**
808 * Constant for use with {@link #orderBy}
809 * @hide
810 */
811 public static final int ORDER_ASCENDING = 1;
812
813 /**
814 * Constant for use with {@link #orderBy}
815 * @hide
816 */
817 public static final int ORDER_DESCENDING = 2;
818
Steve Howard64c48b82010-10-07 17:53:52 -0700819 private long[] mIds = null;
Steve Howarda2709362010-07-02 17:12:48 -0700820 private Integer mStatusFlags = null;
Ben Lince763d82016-05-02 16:45:45 -0700821 private String mFilterString = null;
Vasu Norief7e33b2010-10-20 13:26:02 -0700822 private String mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
Steve Howardf054e192010-09-01 18:26:26 -0700823 private int mOrderDirection = ORDER_DESCENDING;
Steve Howard90fb15a2010-09-09 16:13:41 -0700824 private boolean mOnlyIncludeVisibleInDownloadsUi = false;
Steve Howarda2709362010-07-02 17:12:48 -0700825
826 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700827 * Include only the downloads with the given IDs.
Steve Howarda2709362010-07-02 17:12:48 -0700828 * @return this object
829 */
Steve Howard64c48b82010-10-07 17:53:52 -0700830 public Query setFilterById(long... ids) {
831 mIds = ids;
Steve Howarda2709362010-07-02 17:12:48 -0700832 return this;
833 }
834
835 /**
Ben Lince763d82016-05-02 16:45:45 -0700836 *
837 * Include only the downloads that contains the given string in its name.
838 * @return this object
839 * @hide
840 */
841 public Query setFilterByString(@Nullable String filter) {
842 mFilterString = filter;
843 return this;
844 }
845
846 /**
Steve Howarda2709362010-07-02 17:12:48 -0700847 * Include only downloads with status matching any the given status flags.
848 * @param flags any combination of the STATUS_* bit flags
849 * @return this object
850 */
851 public Query setFilterByStatus(int flags) {
852 mStatusFlags = flags;
853 return this;
854 }
855
856 /**
Steve Howard90fb15a2010-09-09 16:13:41 -0700857 * Controls whether this query includes downloads not visible in the system's Downloads UI.
858 * @param value if true, this query will only include downloads that should be displayed in
859 * the system's Downloads UI; if false (the default), this query will include
860 * both visible and invisible downloads.
861 * @return this object
862 * @hide
863 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100864 @UnsupportedAppUsage
Steve Howard90fb15a2010-09-09 16:13:41 -0700865 public Query setOnlyIncludeVisibleInDownloadsUi(boolean value) {
866 mOnlyIncludeVisibleInDownloadsUi = value;
867 return this;
868 }
869
870 /**
Steve Howardf054e192010-09-01 18:26:26 -0700871 * Change the sort order of the returned Cursor.
872 *
873 * @param column one of the COLUMN_* constants; currently, only
874 * {@link #COLUMN_LAST_MODIFIED_TIMESTAMP} and {@link #COLUMN_TOTAL_SIZE_BYTES} are
875 * supported.
876 * @param direction either {@link #ORDER_ASCENDING} or {@link #ORDER_DESCENDING}
877 * @return this object
878 * @hide
879 */
Mathew Inwood8c854f82018-09-14 12:35:36 +0100880 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Steve Howardf054e192010-09-01 18:26:26 -0700881 public Query orderBy(String column, int direction) {
882 if (direction != ORDER_ASCENDING && direction != ORDER_DESCENDING) {
883 throw new IllegalArgumentException("Invalid direction: " + direction);
884 }
885
886 if (column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP)) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700887 mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
Steve Howardf054e192010-09-01 18:26:26 -0700888 } else if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700889 mOrderByColumn = Downloads.Impl.COLUMN_TOTAL_BYTES;
Steve Howardf054e192010-09-01 18:26:26 -0700890 } else {
891 throw new IllegalArgumentException("Cannot order by " + column);
892 }
893 mOrderDirection = direction;
894 return this;
895 }
896
897 /**
Steve Howarda2709362010-07-02 17:12:48 -0700898 * Run this query using the given ContentResolver.
899 * @param projection the projection to pass to ContentResolver.query()
900 * @return the Cursor returned by ContentResolver.query()
901 */
Steve Howardeca77fc2010-09-12 18:49:08 -0700902 Cursor runQuery(ContentResolver resolver, String[] projection, Uri baseUri) {
903 Uri uri = baseUri;
Steve Howard90fb15a2010-09-09 16:13:41 -0700904 List<String> selectionParts = new ArrayList<String>();
Steve Howard64c48b82010-10-07 17:53:52 -0700905 String[] selectionArgs = null;
Steve Howarda2709362010-07-02 17:12:48 -0700906
Ben Lince763d82016-05-02 16:45:45 -0700907 int whereArgsCount = (mIds == null) ? 0 : mIds.length;
908 whereArgsCount = (mFilterString == null) ? whereArgsCount : whereArgsCount + 1;
909 selectionArgs = new String[whereArgsCount];
910
911 if (whereArgsCount > 0) {
912 if (mIds != null) {
913 selectionParts.add(getWhereClauseForIds(mIds));
914 getWhereArgsForIds(mIds, selectionArgs);
915 }
916
917 if (mFilterString != null) {
918 selectionParts.add(Downloads.Impl.COLUMN_TITLE + " LIKE ?");
919 selectionArgs[selectionArgs.length - 1] = "%" + mFilterString + "%";
920 }
Steve Howarda2709362010-07-02 17:12:48 -0700921 }
922
923 if (mStatusFlags != null) {
924 List<String> parts = new ArrayList<String>();
925 if ((mStatusFlags & STATUS_PENDING) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700926 parts.add(statusClause("=", Downloads.Impl.STATUS_PENDING));
Steve Howarda2709362010-07-02 17:12:48 -0700927 }
928 if ((mStatusFlags & STATUS_RUNNING) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700929 parts.add(statusClause("=", Downloads.Impl.STATUS_RUNNING));
Steve Howarda2709362010-07-02 17:12:48 -0700930 }
931 if ((mStatusFlags & STATUS_PAUSED) != 0) {
Steve Howard3e8c1d32010-09-29 17:03:32 -0700932 parts.add(statusClause("=", Downloads.Impl.STATUS_PAUSED_BY_APP));
933 parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_TO_RETRY));
934 parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_FOR_NETWORK));
935 parts.add(statusClause("=", Downloads.Impl.STATUS_QUEUED_FOR_WIFI));
Steve Howarda2709362010-07-02 17:12:48 -0700936 }
937 if ((mStatusFlags & STATUS_SUCCESSFUL) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700938 parts.add(statusClause("=", Downloads.Impl.STATUS_SUCCESS));
Steve Howarda2709362010-07-02 17:12:48 -0700939 }
940 if ((mStatusFlags & STATUS_FAILED) != 0) {
941 parts.add("(" + statusClause(">=", 400)
942 + " AND " + statusClause("<", 600) + ")");
943 }
Steve Howard90fb15a2010-09-09 16:13:41 -0700944 selectionParts.add(joinStrings(" OR ", parts));
Steve Howarda2709362010-07-02 17:12:48 -0700945 }
Steve Howardf054e192010-09-01 18:26:26 -0700946
Steve Howard90fb15a2010-09-09 16:13:41 -0700947 if (mOnlyIncludeVisibleInDownloadsUi) {
948 selectionParts.add(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI + " != '0'");
949 }
950
Vasu Nori216fa222010-10-12 23:08:13 -0700951 // only return rows which are not marked 'deleted = 1'
952 selectionParts.add(Downloads.Impl.COLUMN_DELETED + " != '1'");
953
Steve Howard90fb15a2010-09-09 16:13:41 -0700954 String selection = joinStrings(" AND ", selectionParts);
Steve Howardf054e192010-09-01 18:26:26 -0700955 String orderDirection = (mOrderDirection == ORDER_ASCENDING ? "ASC" : "DESC");
956 String orderBy = mOrderByColumn + " " + orderDirection;
957
Steve Howard64c48b82010-10-07 17:53:52 -0700958 return resolver.query(uri, projection, selection, selectionArgs, orderBy);
Steve Howarda2709362010-07-02 17:12:48 -0700959 }
960
961 private String joinStrings(String joiner, Iterable<String> parts) {
962 StringBuilder builder = new StringBuilder();
963 boolean first = true;
964 for (String part : parts) {
965 if (!first) {
966 builder.append(joiner);
967 }
968 builder.append(part);
969 first = false;
970 }
971 return builder.toString();
972 }
973
974 private String statusClause(String operator, int value) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700975 return Downloads.Impl.COLUMN_STATUS + operator + "'" + value + "'";
Steve Howarda2709362010-07-02 17:12:48 -0700976 }
977 }
978
Jeff Sharkey60cfad82016-01-05 17:30:57 -0700979 private final ContentResolver mResolver;
980 private final String mPackageName;
Jeff Sharkey60cfad82016-01-05 17:30:57 -0700981
Steve Howardeca77fc2010-09-12 18:49:08 -0700982 private Uri mBaseUri = Downloads.Impl.CONTENT_URI;
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -0700983 private boolean mAccessFilename;
Steve Howarda2709362010-07-02 17:12:48 -0700984
985 /**
986 * @hide
987 */
Jeff Sharkey60cfad82016-01-05 17:30:57 -0700988 public DownloadManager(Context context) {
989 mResolver = context.getContentResolver();
990 mPackageName = context.getPackageName();
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -0700991
992 // Callers can access filename columns when targeting old platform
993 // versions; otherwise we throw telling them it's deprecated.
994 mAccessFilename = context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N;
Steve Howarda2709362010-07-02 17:12:48 -0700995 }
996
997 /**
Steve Howardeca77fc2010-09-12 18:49:08 -0700998 * Makes this object access the download provider through /all_downloads URIs rather than
999 * /my_downloads URIs, for clients that have permission to do so.
1000 * @hide
1001 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001002 @UnsupportedAppUsage
Steve Howardeca77fc2010-09-12 18:49:08 -07001003 public void setAccessAllDownloads(boolean accessAllDownloads) {
1004 if (accessAllDownloads) {
1005 mBaseUri = Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI;
1006 } else {
1007 mBaseUri = Downloads.Impl.CONTENT_URI;
1008 }
1009 }
1010
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001011 /** {@hide} */
Mathew Inwood8c854f82018-09-14 12:35:36 +01001012 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001013 public void setAccessFilename(boolean accessFilename) {
1014 mAccessFilename = accessFilename;
1015 }
1016
Steve Howardeca77fc2010-09-12 18:49:08 -07001017 /**
Steve Howarda2709362010-07-02 17:12:48 -07001018 * Enqueue a new download. The download will start automatically once the download manager is
1019 * ready to execute it and connectivity is available.
1020 *
1021 * @param request the parameters specifying this download
1022 * @return an ID for the download, unique across the system. This ID is used to make future
1023 * calls related to this download.
1024 */
1025 public long enqueue(Request request) {
Steve Howardb8e07a52010-07-21 14:53:21 -07001026 ContentValues values = request.toContentValues(mPackageName);
Vasu Norief7e33b2010-10-20 13:26:02 -07001027 Uri downloadUri = mResolver.insert(Downloads.Impl.CONTENT_URI, values);
Steve Howarda2709362010-07-02 17:12:48 -07001028 long id = Long.parseLong(downloadUri.getLastPathSegment());
1029 return id;
1030 }
1031
1032 /**
Vasu Nori216fa222010-10-12 23:08:13 -07001033 * Marks the specified download as 'to be deleted'. This is done when a completed download
1034 * is to be removed but the row was stored without enough info to delete the corresponding
1035 * metadata from Mediaprovider database. Actual cleanup of this row is done in DownloadService.
1036 *
1037 * @param ids the IDs of the downloads to be marked 'deleted'
1038 * @return the number of downloads actually updated
1039 * @hide
1040 */
1041 public int markRowDeleted(long... ids) {
1042 if (ids == null || ids.length == 0) {
1043 // called with nothing to remove!
1044 throw new IllegalArgumentException("input param 'ids' can't be null");
1045 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001046 return mResolver.delete(mBaseUri, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
Vasu Nori216fa222010-10-12 23:08:13 -07001047 }
1048
1049 /**
Steve Howard64c48b82010-10-07 17:53:52 -07001050 * Cancel downloads and remove them from the download manager. Each download will be stopped if
Vasu Nori17ee56c2011-02-28 08:35:39 -08001051 * it was running, and it will no longer be accessible through the download manager.
1052 * If there is a downloaded file, partial or complete, it is deleted.
Steve Howarda2709362010-07-02 17:12:48 -07001053 *
Steve Howard64c48b82010-10-07 17:53:52 -07001054 * @param ids the IDs of the downloads to remove
1055 * @return the number of downloads actually removed
Steve Howarda2709362010-07-02 17:12:48 -07001056 */
Steve Howard64c48b82010-10-07 17:53:52 -07001057 public int remove(long... ids) {
Vasu Norie16c43b2010-11-06 18:48:08 -07001058 return markRowDeleted(ids);
Steve Howarda2709362010-07-02 17:12:48 -07001059 }
1060
1061 /**
1062 * Query the download manager about downloads that have been requested.
1063 * @param query parameters specifying filters for this query
1064 * @return a Cursor over the result set of downloads, with columns consisting of all the
1065 * COLUMN_* constants.
1066 */
1067 public Cursor query(Query query) {
Sudheer Shankae93db512019-01-11 16:05:28 -08001068 return query(query, UNDERLYING_COLUMNS);
1069 }
1070
1071 /** @hide */
1072 public Cursor query(Query query, String[] projection) {
1073 Cursor underlyingCursor = query.runQuery(mResolver, projection, mBaseUri);
Steve Howardf054e192010-09-01 18:26:26 -07001074 if (underlyingCursor == null) {
1075 return null;
1076 }
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001077 return new CursorTranslator(underlyingCursor, mBaseUri, mAccessFilename);
Steve Howarda2709362010-07-02 17:12:48 -07001078 }
1079
1080 /**
1081 * Open a downloaded file for reading. The download must have completed.
1082 * @param id the ID of the download
1083 * @return a read-only {@link ParcelFileDescriptor}
1084 * @throws FileNotFoundException if the destination file does not already exist
1085 */
1086 public ParcelFileDescriptor openDownloadedFile(long id) throws FileNotFoundException {
1087 return mResolver.openFileDescriptor(getDownloadUri(id), "r");
1088 }
1089
1090 /**
John Spurlock92a262c2013-11-04 16:25:38 -05001091 * Returns the {@link Uri} of the given downloaded file id, if the file is
1092 * downloaded successfully. Otherwise, null is returned.
Vasu Nori5be894e2010-11-02 21:55:30 -07001093 *
1094 * @param id the id of the downloaded file.
Jeff Sharkeyb11683b2015-07-29 10:15:34 -07001095 * @return the {@link Uri} of the given downloaded file id, if download was
1096 * successful. null otherwise.
Vasu Nori5be894e2010-11-02 21:55:30 -07001097 */
1098 public Uri getUriForDownloadedFile(long id) {
1099 // to check if the file is in cache, get its destination from the database
1100 Query query = new Query().setFilterById(id);
1101 Cursor cursor = null;
1102 try {
1103 cursor = query(query);
1104 if (cursor == null) {
1105 return null;
1106 }
Leon Scrogginsd75e64a2010-12-13 15:48:40 -05001107 if (cursor.moveToFirst()) {
Vasu Nori6e2b2a62010-11-16 17:58:22 -08001108 int status = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_STATUS));
Vasu Nori5be894e2010-11-02 21:55:30 -07001109 if (DownloadManager.STATUS_SUCCESSFUL == status) {
Jeff Sharkeydf42d732016-09-16 16:57:34 -06001110 return ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, id);
Vasu Nori5be894e2010-11-02 21:55:30 -07001111 }
1112 }
1113 } finally {
1114 if (cursor != null) {
1115 cursor.close();
1116 }
1117 }
1118 // downloaded file not found or its status is not 'successfully completed'
1119 return null;
1120 }
1121
1122 /**
John Spurlock92a262c2013-11-04 16:25:38 -05001123 * Returns the media type of the given downloaded file id, if the file was
1124 * downloaded successfully. Otherwise, null is returned.
Vasu Nori6e2b2a62010-11-16 17:58:22 -08001125 *
1126 * @param id the id of the downloaded file.
John Spurlock92a262c2013-11-04 16:25:38 -05001127 * @return the media type of the given downloaded file id, if download was successful. null
Vasu Nori6e2b2a62010-11-16 17:58:22 -08001128 * otherwise.
1129 */
1130 public String getMimeTypeForDownloadedFile(long id) {
1131 Query query = new Query().setFilterById(id);
1132 Cursor cursor = null;
1133 try {
1134 cursor = query(query);
1135 if (cursor == null) {
1136 return null;
1137 }
1138 while (cursor.moveToFirst()) {
1139 return cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_MEDIA_TYPE));
1140 }
1141 } finally {
1142 if (cursor != null) {
1143 cursor.close();
1144 }
1145 }
1146 // downloaded file not found or its status is not 'successfully completed'
1147 return null;
1148 }
1149
1150 /**
Steve Howard64c48b82010-10-07 17:53:52 -07001151 * Restart the given downloads, which must have already completed (successfully or not). This
Steve Howard90fb15a2010-09-09 16:13:41 -07001152 * method will only work when called from within the download manager's process.
Steve Howard64c48b82010-10-07 17:53:52 -07001153 * @param ids the IDs of the downloads
Steve Howard90fb15a2010-09-09 16:13:41 -07001154 * @hide
1155 */
Steve Howard64c48b82010-10-07 17:53:52 -07001156 public void restartDownload(long... ids) {
1157 Cursor cursor = query(new Query().setFilterById(ids));
Steve Howard90fb15a2010-09-09 16:13:41 -07001158 try {
Steve Howard64c48b82010-10-07 17:53:52 -07001159 for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
1160 int status = cursor.getInt(cursor.getColumnIndex(COLUMN_STATUS));
1161 if (status != STATUS_SUCCESSFUL && status != STATUS_FAILED) {
1162 throw new IllegalArgumentException("Cannot restart incomplete download: "
1163 + cursor.getLong(cursor.getColumnIndex(COLUMN_ID)));
1164 }
Steve Howard90fb15a2010-09-09 16:13:41 -07001165 }
1166 } finally {
1167 cursor.close();
1168 }
1169
1170 ContentValues values = new ContentValues();
1171 values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, 0);
1172 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, -1);
1173 values.putNull(Downloads.Impl._DATA);
1174 values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING);
Jeff Sharkey54781202013-01-17 17:27:33 -08001175 values.put(Downloads.Impl.COLUMN_FAILED_CONNECTIONS, 0);
Steve Howard64c48b82010-10-07 17:53:52 -07001176 mResolver.update(mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
Steve Howard90fb15a2010-09-09 16:13:41 -07001177 }
1178
1179 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001180 * Force the given downloads to proceed even if their size is larger than
1181 * {@link #getMaxBytesOverMobile(Context)}.
1182 *
1183 * @hide
1184 */
1185 public void forceDownload(long... ids) {
1186 ContentValues values = new ContentValues();
1187 values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING);
1188 values.put(Downloads.Impl.COLUMN_CONTROL, Downloads.Impl.CONTROL_RUN);
1189 values.put(Downloads.Impl.COLUMN_BYPASS_RECOMMENDED_SIZE_LIMIT, 1);
1190 mResolver.update(mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
1191 }
1192
1193 /**
Vasu Nori0abbf802011-01-17 15:08:14 -08001194 * Returns maximum size, in bytes, of downloads that may go over a mobile connection; or null if
1195 * there's no limit
1196 *
1197 * @param context the {@link Context} to use for accessing the {@link ContentResolver}
1198 * @return maximum size, in bytes, of downloads that may go over a mobile connection; or null if
1199 * there's no limit
1200 */
1201 public static Long getMaxBytesOverMobile(Context context) {
1202 try {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001203 return Settings.Global.getLong(context.getContentResolver(),
1204 Settings.Global.DOWNLOAD_MAX_BYTES_OVER_MOBILE);
Vasu Nori0abbf802011-01-17 15:08:14 -08001205 } catch (SettingNotFoundException exc) {
1206 return null;
1207 }
1208 }
1209
1210 /**
Ben Lin726bf6a2016-04-27 11:38:05 -07001211 * Rename the given download if the download has completed
1212 *
1213 * @param context the {@link Context} to use in case need to update MediaProvider
1214 * @param id the downloaded id
1215 * @param displayName the new name to rename to
1216 * @return true if rename was successful, false otherwise
1217 * @hide
1218 */
1219 public boolean rename(Context context, long id, String displayName) {
1220 if (!FileUtils.isValidFatFilename(displayName)) {
1221 throw new SecurityException(displayName + " is not a valid filename");
1222 }
1223
1224 Query query = new Query().setFilterById(id);
1225 Cursor cursor = null;
1226 String oldDisplayName = null;
1227 String mimeType = null;
1228 try {
1229 cursor = query(query);
1230 if (cursor == null) {
1231 return false;
1232 }
1233 if (cursor.moveToFirst()) {
1234 int status = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_STATUS));
1235 if (DownloadManager.STATUS_SUCCESSFUL != status) {
1236 return false;
1237 }
1238 oldDisplayName = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_TITLE));
1239 mimeType = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_MEDIA_TYPE));
1240 }
1241 } finally {
1242 if (cursor != null) {
1243 cursor.close();
1244 }
1245 }
1246
1247 if (oldDisplayName == null || mimeType == null) {
1248 throw new IllegalStateException(
1249 "Document with id " + id + " does not exist");
1250 }
1251
1252 final File parent = Environment.getExternalStoragePublicDirectory(
1253 Environment.DIRECTORY_DOWNLOADS);
1254
1255 final File before = new File(parent, oldDisplayName);
1256 final File after = new File(parent, displayName);
1257
1258 if (after.exists()) {
1259 throw new IllegalStateException("Already exists " + after);
1260 }
1261 if (!before.renameTo(after)) {
1262 throw new IllegalStateException("Failed to rename to " + after);
1263 }
1264
Ben Lin726bf6a2016-04-27 11:38:05 -07001265 ContentValues values = new ContentValues();
1266 values.put(Downloads.Impl.COLUMN_TITLE, displayName);
1267 values.put(Downloads.Impl._DATA, after.toString());
1268 values.putNull(Downloads.Impl.COLUMN_MEDIAPROVIDER_URI);
1269 long[] ids = {id};
1270
1271 return (mResolver.update(mBaseUri, values, getWhereClauseForIds(ids),
1272 getWhereArgsForIds(ids)) == 1);
1273 }
1274
1275 /**
Vasu Nori0abbf802011-01-17 15:08:14 -08001276 * Returns recommended maximum size, in bytes, of downloads that may go over a mobile
1277 * connection; or null if there's no recommended limit. The user will have the option to bypass
1278 * this limit.
1279 *
1280 * @param context the {@link Context} to use for accessing the {@link ContentResolver}
1281 * @return recommended maximum size, in bytes, of downloads that may go over a mobile
1282 * connection; or null if there's no recommended limit.
1283 */
1284 public static Long getRecommendedMaxBytesOverMobile(Context context) {
1285 try {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001286 return Settings.Global.getLong(context.getContentResolver(),
1287 Settings.Global.DOWNLOAD_RECOMMENDED_MAX_BYTES_OVER_MOBILE);
Vasu Nori0abbf802011-01-17 15:08:14 -08001288 } catch (SettingNotFoundException exc) {
1289 return null;
1290 }
1291 }
Vasu Noric0e50752011-01-20 17:57:54 -08001292
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001293 /** {@hide} */
1294 public static boolean isActiveNetworkExpensive(Context context) {
1295 // TODO: connect to NetworkPolicyManager
1296 return false;
1297 }
1298
1299 /** {@hide} */
1300 public static long getActiveNetworkWarningBytes(Context context) {
1301 // TODO: connect to NetworkPolicyManager
1302 return -1;
1303 }
1304
Vasu Noric0e50752011-01-20 17:57:54 -08001305 /**
1306 * Adds a file to the downloads database system, so it could appear in Downloads App
1307 * (and thus become eligible for management by the Downloads App).
1308 * <p>
1309 * It is helpful to make the file scannable by MediaScanner by setting the param
1310 * isMediaScannerScannable to true. It makes the file visible in media managing
1311 * applications such as Gallery App, which could be a useful purpose of using this API.
1312 *
1313 * @param title the title that would appear for this file in Downloads App.
1314 * @param description the description that would appear for this file in Downloads App.
1315 * @param isMediaScannerScannable true if the file is to be scanned by MediaScanner. Files
1316 * scanned by MediaScanner appear in the applications used to view media (for example,
Sudheer Shanka684c02a2019-01-29 17:41:15 -08001317 * Gallery app).
Vasu Noric0e50752011-01-20 17:57:54 -08001318 * @param mimeType mimetype of the file.
1319 * @param path absolute pathname to the file. The file should be world-readable, so that it can
1320 * be managed by the Downloads App and any other app that is used to read it (for example,
1321 * Gallery app to display the file, if the file contents represent a video/image).
1322 * @param length length of the downloaded file
Vasu Norif9e85232011-02-10 14:59:54 -08001323 * @param showNotification true if a notification is to be sent, false otherwise
Vasu Noric0e50752011-01-20 17:57:54 -08001324 * @return an ID for the download entry added to the downloads app, unique across the system
1325 * This ID is used to make future calls related to this download.
1326 */
Vasu Nori37281302011-03-07 11:25:01 -08001327 public long addCompletedDownload(String title, String description,
Vasu Norif9e85232011-02-10 14:59:54 -08001328 boolean isMediaScannerScannable, String mimeType, String path, long length,
1329 boolean showNotification) {
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001330 return addCompletedDownload(title, description, isMediaScannerScannable, mimeType, path,
Edward Cunninghamabb2c5a2016-03-25 20:56:31 +00001331 length, showNotification, false, null, null);
1332 }
1333
1334 /**
1335 * Adds a file to the downloads database system, so it could appear in Downloads App
1336 * (and thus become eligible for management by the Downloads App).
1337 * <p>
1338 * It is helpful to make the file scannable by MediaScanner by setting the param
1339 * isMediaScannerScannable to true. It makes the file visible in media managing
1340 * applications such as Gallery App, which could be a useful purpose of using this API.
1341 *
1342 * @param title the title that would appear for this file in Downloads App.
1343 * @param description the description that would appear for this file in Downloads App.
1344 * @param isMediaScannerScannable true if the file is to be scanned by MediaScanner. Files
1345 * scanned by MediaScanner appear in the applications used to view media (for example,
Sudheer Shanka684c02a2019-01-29 17:41:15 -08001346 * Gallery app).
Edward Cunninghamabb2c5a2016-03-25 20:56:31 +00001347 * @param mimeType mimetype of the file.
1348 * @param path absolute pathname to the file. The file should be world-readable, so that it can
1349 * be managed by the Downloads App and any other app that is used to read it (for example,
1350 * Gallery app to display the file, if the file contents represent a video/image).
1351 * @param length length of the downloaded file
1352 * @param showNotification true if a notification is to be sent, false otherwise
1353 * @param uri the original HTTP URI of the download
1354 * @param referer the HTTP Referer for the download
1355 * @return an ID for the download entry added to the downloads app, unique across the system
1356 * This ID is used to make future calls related to this download.
1357 */
1358 public long addCompletedDownload(String title, String description,
1359 boolean isMediaScannerScannable, String mimeType, String path, long length,
1360 boolean showNotification, Uri uri, Uri referer) {
1361 return addCompletedDownload(title, description, isMediaScannerScannable, mimeType, path,
1362 length, showNotification, false, uri, referer);
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001363 }
1364
1365 /** {@hide} */
1366 public long addCompletedDownload(String title, String description,
1367 boolean isMediaScannerScannable, String mimeType, String path, long length,
1368 boolean showNotification, boolean allowWrite) {
Edward Cunninghamabb2c5a2016-03-25 20:56:31 +00001369 return addCompletedDownload(title, description, isMediaScannerScannable, mimeType, path,
1370 length, showNotification, allowWrite, null, null);
1371 }
1372
1373 /** {@hide} */
1374 public long addCompletedDownload(String title, String description,
1375 boolean isMediaScannerScannable, String mimeType, String path, long length,
1376 boolean showNotification, boolean allowWrite, Uri uri, Uri referer) {
Vasu Noric0e50752011-01-20 17:57:54 -08001377 // make sure the input args are non-null/non-zero
1378 validateArgumentIsNonEmpty("title", title);
1379 validateArgumentIsNonEmpty("description", description);
1380 validateArgumentIsNonEmpty("path", path);
1381 validateArgumentIsNonEmpty("mimeType", mimeType);
Jeff Sharkey33f95ed2012-05-02 17:07:54 -07001382 if (length < 0) {
Vasu Noric0e50752011-01-20 17:57:54 -08001383 throw new IllegalArgumentException(" invalid value for param: totalBytes");
1384 }
1385
1386 // if there is already an entry with the given path name in downloads.db, return its id
Edward Cunninghamabb2c5a2016-03-25 20:56:31 +00001387 Request request;
1388 if (uri != null) {
1389 request = new Request(uri);
1390 } else {
1391 request = new Request(NON_DOWNLOADMANAGER_DOWNLOAD);
1392 }
1393 request.setTitle(title)
Vasu Noric0e50752011-01-20 17:57:54 -08001394 .setDescription(description)
1395 .setMimeType(mimeType);
Edward Cunninghamabb2c5a2016-03-25 20:56:31 +00001396 if (referer != null) {
1397 request.addRequestHeader("Referer", referer.toString());
1398 }
Vasu Noric0e50752011-01-20 17:57:54 -08001399 ContentValues values = request.toContentValues(null);
1400 values.put(Downloads.Impl.COLUMN_DESTINATION,
1401 Downloads.Impl.DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD);
1402 values.put(Downloads.Impl._DATA, path);
1403 values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_SUCCESS);
1404 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, length);
1405 values.put(Downloads.Impl.COLUMN_MEDIA_SCANNED,
1406 (isMediaScannerScannable) ? Request.SCANNABLE_VALUE_YES :
1407 Request.SCANNABLE_VALUE_NO);
Vasu Norif9e85232011-02-10 14:59:54 -08001408 values.put(Downloads.Impl.COLUMN_VISIBILITY, (showNotification) ?
1409 Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION : Request.VISIBILITY_HIDDEN);
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001410 values.put(Downloads.Impl.COLUMN_ALLOW_WRITE, allowWrite ? 1 : 0);
Vasu Noric0e50752011-01-20 17:57:54 -08001411 Uri downloadUri = mResolver.insert(Downloads.Impl.CONTENT_URI, values);
1412 if (downloadUri == null) {
1413 return -1;
1414 }
1415 return Long.parseLong(downloadUri.getLastPathSegment());
1416 }
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001417
Vasu Noric0e50752011-01-20 17:57:54 -08001418 private static final String NON_DOWNLOADMANAGER_DOWNLOAD =
1419 "non-dwnldmngr-download-dont-retry2download";
1420
1421 private static void validateArgumentIsNonEmpty(String paramName, String val) {
1422 if (TextUtils.isEmpty(val)) {
1423 throw new IllegalArgumentException(paramName + " can't be null");
1424 }
1425 }
1426
Vasu Nori0abbf802011-01-17 15:08:14 -08001427 /**
Steve Howarda2709362010-07-02 17:12:48 -07001428 * Get the DownloadProvider URI for the download with the given ID.
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001429 *
1430 * @hide
Steve Howarda2709362010-07-02 17:12:48 -07001431 */
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001432 public Uri getDownloadUri(long id) {
Jeff Sharkey15471942016-09-16 12:04:05 -06001433 return ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, id);
Steve Howarda2709362010-07-02 17:12:48 -07001434 }
1435
1436 /**
Steve Howard64c48b82010-10-07 17:53:52 -07001437 * Get a parameterized SQL WHERE clause to select a bunch of IDs.
1438 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001439 @UnsupportedAppUsage
Steve Howard64c48b82010-10-07 17:53:52 -07001440 static String getWhereClauseForIds(long[] ids) {
1441 StringBuilder whereClause = new StringBuilder();
Vasu Norie7be6bd2010-10-10 14:58:08 -07001442 whereClause.append("(");
Steve Howard64c48b82010-10-07 17:53:52 -07001443 for (int i = 0; i < ids.length; i++) {
1444 if (i > 0) {
Vasu Norie7be6bd2010-10-10 14:58:08 -07001445 whereClause.append("OR ");
Steve Howard64c48b82010-10-07 17:53:52 -07001446 }
Vasu Norie7be6bd2010-10-10 14:58:08 -07001447 whereClause.append(Downloads.Impl._ID);
1448 whereClause.append(" = ? ");
Steve Howard64c48b82010-10-07 17:53:52 -07001449 }
1450 whereClause.append(")");
1451 return whereClause.toString();
1452 }
1453
1454 /**
1455 * Get the selection args for a clause returned by {@link #getWhereClauseForIds(long[])}.
1456 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001457 @UnsupportedAppUsage
Steve Howard64c48b82010-10-07 17:53:52 -07001458 static String[] getWhereArgsForIds(long[] ids) {
1459 String[] whereArgs = new String[ids.length];
Ben Lince763d82016-05-02 16:45:45 -07001460 return getWhereArgsForIds(ids, whereArgs);
Steve Howard64c48b82010-10-07 17:53:52 -07001461 }
1462
1463 /**
Ben Lince763d82016-05-02 16:45:45 -07001464 * Get selection args for a clause returned by {@link #getWhereClauseForIds(long[])}
1465 * and write it to the supplied args array.
1466 */
1467 static String[] getWhereArgsForIds(long[] ids, String[] args) {
1468 assert(args.length >= ids.length);
1469 for (int i = 0; i < ids.length; i++) {
1470 args[i] = Long.toString(ids[i]);
1471 }
1472 return args;
1473 }
1474
1475
1476 /**
Steve Howarda2709362010-07-02 17:12:48 -07001477 * This class wraps a cursor returned by DownloadProvider -- the "underlying cursor" -- and
1478 * presents a different set of columns, those defined in the DownloadManager.COLUMN_* constants.
1479 * Some columns correspond directly to underlying values while others are computed from
1480 * underlying data.
1481 */
1482 private static class CursorTranslator extends CursorWrapper {
Jeff Sharkey60cfad82016-01-05 17:30:57 -07001483 private final Uri mBaseUri;
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001484 private final boolean mAccessFilename;
Steve Howardeca77fc2010-09-12 18:49:08 -07001485
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001486 public CursorTranslator(Cursor cursor, Uri baseUri, boolean accessFilename) {
Steve Howarda2709362010-07-02 17:12:48 -07001487 super(cursor);
Steve Howardeca77fc2010-09-12 18:49:08 -07001488 mBaseUri = baseUri;
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001489 mAccessFilename = accessFilename;
Steve Howarda2709362010-07-02 17:12:48 -07001490 }
1491
1492 @Override
Steve Howarda2709362010-07-02 17:12:48 -07001493 public int getInt(int columnIndex) {
1494 return (int) getLong(columnIndex);
1495 }
1496
1497 @Override
1498 public long getLong(int columnIndex) {
Vasu Norie16c43b2010-11-06 18:48:08 -07001499 if (getColumnName(columnIndex).equals(COLUMN_REASON)) {
1500 return getReason(super.getInt(getColumnIndex(Downloads.Impl.COLUMN_STATUS)));
1501 } else if (getColumnName(columnIndex).equals(COLUMN_STATUS)) {
1502 return translateStatus(super.getInt(getColumnIndex(Downloads.Impl.COLUMN_STATUS)));
1503 } else {
1504 return super.getLong(columnIndex);
1505 }
Steve Howarda2709362010-07-02 17:12:48 -07001506 }
1507
1508 @Override
1509 public String getString(int columnIndex) {
Jeff Sharkey60cfad82016-01-05 17:30:57 -07001510 final String columnName = getColumnName(columnIndex);
1511 switch (columnName) {
1512 case COLUMN_LOCAL_URI:
1513 return getLocalUri();
1514 case COLUMN_LOCAL_FILENAME:
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001515 if (!mAccessFilename) {
Jeff Sharkey0c2ccd02016-03-22 10:05:47 -06001516 throw new SecurityException(
Jeff Sharkey60cfad82016-01-05 17:30:57 -07001517 "COLUMN_LOCAL_FILENAME is deprecated;"
1518 + " use ContentResolver.openFileDescriptor() instead");
1519 }
1520 default:
1521 return super.getString(columnIndex);
1522 }
Steve Howardeca77fc2010-09-12 18:49:08 -07001523 }
1524
1525 private String getLocalUri() {
Vasu Norie16c43b2010-11-06 18:48:08 -07001526 long destinationType = getLong(getColumnIndex(Downloads.Impl.COLUMN_DESTINATION));
1527 if (destinationType == Downloads.Impl.DESTINATION_FILE_URI ||
Vasu Noric0e50752011-01-20 17:57:54 -08001528 destinationType == Downloads.Impl.DESTINATION_EXTERNAL ||
1529 destinationType == Downloads.Impl.DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD) {
Jeff Sharkey281c1822016-03-30 19:46:42 -06001530 String localPath = super.getString(getColumnIndex(COLUMN_LOCAL_FILENAME));
Steve Howard99047d72010-09-29 17:41:37 -07001531 if (localPath == null) {
1532 return null;
1533 }
1534 return Uri.fromFile(new File(localPath)).toString();
Steve Howardbb0d23b2010-09-22 18:56:29 -07001535 }
1536
Steve Howardeca77fc2010-09-12 18:49:08 -07001537 // return content URI for cache download
Vasu Norie16c43b2010-11-06 18:48:08 -07001538 long downloadId = getLong(getColumnIndex(Downloads.Impl._ID));
Jeff Sharkey15471942016-09-16 12:04:05 -06001539 return ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, downloadId).toString();
Steve Howarda2709362010-07-02 17:12:48 -07001540 }
1541
Steve Howard3e8c1d32010-09-29 17:03:32 -07001542 private long getReason(int status) {
1543 switch (translateStatus(status)) {
1544 case STATUS_FAILED:
1545 return getErrorCode(status);
1546
1547 case STATUS_PAUSED:
1548 return getPausedReason(status);
1549
1550 default:
1551 return 0; // arbitrary value when status is not an error
Steve Howarda2709362010-07-02 17:12:48 -07001552 }
Steve Howard3e8c1d32010-09-29 17:03:32 -07001553 }
1554
1555 private long getPausedReason(int status) {
1556 switch (status) {
1557 case Downloads.Impl.STATUS_WAITING_TO_RETRY:
1558 return PAUSED_WAITING_TO_RETRY;
1559
1560 case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
1561 return PAUSED_WAITING_FOR_NETWORK;
1562
1563 case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
1564 return PAUSED_QUEUED_FOR_WIFI;
1565
1566 default:
1567 return PAUSED_UNKNOWN;
1568 }
1569 }
1570
1571 private long getErrorCode(int status) {
Steve Howard33bbd122010-08-02 17:51:29 -07001572 if ((400 <= status && status < Downloads.Impl.MIN_ARTIFICIAL_ERROR_STATUS)
1573 || (500 <= status && status < 600)) {
Steve Howarda2709362010-07-02 17:12:48 -07001574 // HTTP status code
1575 return status;
1576 }
1577
1578 switch (status) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001579 case Downloads.Impl.STATUS_FILE_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001580 return ERROR_FILE_ERROR;
1581
Vasu Norief7e33b2010-10-20 13:26:02 -07001582 case Downloads.Impl.STATUS_UNHANDLED_HTTP_CODE:
1583 case Downloads.Impl.STATUS_UNHANDLED_REDIRECT:
Steve Howarda2709362010-07-02 17:12:48 -07001584 return ERROR_UNHANDLED_HTTP_CODE;
1585
Vasu Norief7e33b2010-10-20 13:26:02 -07001586 case Downloads.Impl.STATUS_HTTP_DATA_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001587 return ERROR_HTTP_DATA_ERROR;
1588
Vasu Norief7e33b2010-10-20 13:26:02 -07001589 case Downloads.Impl.STATUS_TOO_MANY_REDIRECTS:
Steve Howarda2709362010-07-02 17:12:48 -07001590 return ERROR_TOO_MANY_REDIRECTS;
1591
Vasu Norief7e33b2010-10-20 13:26:02 -07001592 case Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001593 return ERROR_INSUFFICIENT_SPACE;
1594
Vasu Norief7e33b2010-10-20 13:26:02 -07001595 case Downloads.Impl.STATUS_DEVICE_NOT_FOUND_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001596 return ERROR_DEVICE_NOT_FOUND;
1597
Steve Howard33bbd122010-08-02 17:51:29 -07001598 case Downloads.Impl.STATUS_CANNOT_RESUME:
1599 return ERROR_CANNOT_RESUME;
1600
Steve Howarda9e87c92010-09-16 12:02:03 -07001601 case Downloads.Impl.STATUS_FILE_ALREADY_EXISTS_ERROR:
1602 return ERROR_FILE_ALREADY_EXISTS;
1603
Steve Howarda2709362010-07-02 17:12:48 -07001604 default:
1605 return ERROR_UNKNOWN;
1606 }
1607 }
1608
Steve Howard3e8c1d32010-09-29 17:03:32 -07001609 private int translateStatus(int status) {
Steve Howarda2709362010-07-02 17:12:48 -07001610 switch (status) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001611 case Downloads.Impl.STATUS_PENDING:
Steve Howarda2709362010-07-02 17:12:48 -07001612 return STATUS_PENDING;
1613
Vasu Norief7e33b2010-10-20 13:26:02 -07001614 case Downloads.Impl.STATUS_RUNNING:
Steve Howarda2709362010-07-02 17:12:48 -07001615 return STATUS_RUNNING;
1616
Steve Howard3e8c1d32010-09-29 17:03:32 -07001617 case Downloads.Impl.STATUS_PAUSED_BY_APP:
1618 case Downloads.Impl.STATUS_WAITING_TO_RETRY:
1619 case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
1620 case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
Steve Howarda2709362010-07-02 17:12:48 -07001621 return STATUS_PAUSED;
1622
Vasu Norief7e33b2010-10-20 13:26:02 -07001623 case Downloads.Impl.STATUS_SUCCESS:
Steve Howarda2709362010-07-02 17:12:48 -07001624 return STATUS_SUCCESSFUL;
1625
1626 default:
Vasu Norief7e33b2010-10-20 13:26:02 -07001627 assert Downloads.Impl.isStatusError(status);
Steve Howarda2709362010-07-02 17:12:48 -07001628 return STATUS_FAILED;
1629 }
1630 }
1631 }
1632}