blob: 462f66f38def2ad06eae56248ae78d2ce68349e7 [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;
21import android.annotation.SdkConstant.SdkConstantType;
Steve Howarda2709362010-07-02 17:12:48 -070022import android.content.ContentResolver;
Steve Howardeca77fc2010-09-12 18:49:08 -070023import android.content.ContentUris;
Steve Howarda2709362010-07-02 17:12:48 -070024import android.content.ContentValues;
Steve Howard4f564cd2010-09-22 15:57:25 -070025import android.content.Context;
Ben Lin726bf6a2016-04-27 11:38:05 -070026import android.content.Intent;
Steve Howarda2709362010-07-02 17:12:48 -070027import android.database.Cursor;
28import android.database.CursorWrapper;
Steve Howardd58429f2010-09-27 16:32:39 -070029import android.net.ConnectivityManager;
Jeff Sharkey1a303952011-06-16 13:04:20 -070030import android.net.NetworkPolicyManager;
Steve Howardd58429f2010-09-27 16:32:39 -070031import android.net.Uri;
Jeff Sharkey60cfad82016-01-05 17:30:57 -070032import android.os.Build;
Steve Howard4f564cd2010-09-22 15:57:25 -070033import android.os.Environment;
Ben Lin726bf6a2016-04-27 11:38:05 -070034import android.os.FileUtils;
Steve Howarda2709362010-07-02 17:12:48 -070035import android.os.ParcelFileDescriptor;
36import android.provider.Downloads;
Vasu Nori0abbf802011-01-17 15:08:14 -080037import android.provider.Settings;
Ben Lin726bf6a2016-04-27 11:38:05 -070038import android.provider.MediaStore.Images;
Vasu Nori0abbf802011-01-17 15:08:14 -080039import android.provider.Settings.SettingNotFoundException;
Vasu Noric0e50752011-01-20 17:57:54 -080040import android.text.TextUtils;
Steve Howard4f564cd2010-09-22 15:57:25 -070041import android.util.Pair;
Steve Howarda2709362010-07-02 17:12:48 -070042
Steve Howard4f564cd2010-09-22 15:57:25 -070043import java.io.File;
Steve Howarda2709362010-07-02 17:12:48 -070044import java.io.FileNotFoundException;
45import java.util.ArrayList;
Steve Howarda2709362010-07-02 17:12:48 -070046import java.util.List;
Steve Howarda2709362010-07-02 17:12:48 -070047
48/**
49 * The download manager is a system service that handles long-running HTTP downloads. Clients may
50 * request that a URI be downloaded to a particular destination file. The download manager will
51 * conduct the download in the background, taking care of HTTP interactions and retrying downloads
52 * after failures or across connectivity changes and system reboots.
53 *
54 * Instances of this class should be obtained through
55 * {@link android.content.Context#getSystemService(String)} by passing
56 * {@link android.content.Context#DOWNLOAD_SERVICE}.
Steve Howard610c4352010-09-30 18:30:04 -070057 *
58 * Apps that request downloads through this API should register a broadcast receiver for
59 * {@link #ACTION_NOTIFICATION_CLICKED} to appropriately handle when the user clicks on a running
60 * download in a notification or from the downloads UI.
Nicolas Falliere9530e3a2012-06-18 17:21:06 -070061 *
62 * Note that the application must have the {@link android.Manifest.permission#INTERNET}
63 * permission to use this class.
Steve Howarda2709362010-07-02 17:12:48 -070064 */
65public class DownloadManager {
Vasu Norie7be6bd2010-10-10 14:58:08 -070066
Steve Howarda2709362010-07-02 17:12:48 -070067 /**
68 * An identifier for a particular download, unique across the system. Clients use this ID to
69 * make subsequent calls related to the download.
70 */
Vasu Norief7e33b2010-10-20 13:26:02 -070071 public final static String COLUMN_ID = Downloads.Impl._ID;
Steve Howarda2709362010-07-02 17:12:48 -070072
73 /**
Steve Howard8651bd52010-08-03 12:35:32 -070074 * The client-supplied title for this download. This will be displayed in system notifications.
75 * Defaults to the empty string.
Steve Howarda2709362010-07-02 17:12:48 -070076 */
Vasu Norief7e33b2010-10-20 13:26:02 -070077 public final static String COLUMN_TITLE = Downloads.Impl.COLUMN_TITLE;
Steve Howarda2709362010-07-02 17:12:48 -070078
79 /**
80 * The client-supplied description of this download. This will be displayed in system
Steve Howard8651bd52010-08-03 12:35:32 -070081 * notifications. Defaults to the empty string.
Steve Howarda2709362010-07-02 17:12:48 -070082 */
Vasu Norief7e33b2010-10-20 13:26:02 -070083 public final static String COLUMN_DESCRIPTION = Downloads.Impl.COLUMN_DESCRIPTION;
Steve Howarda2709362010-07-02 17:12:48 -070084
85 /**
86 * URI to be downloaded.
87 */
Vasu Norief7e33b2010-10-20 13:26:02 -070088 public final static String COLUMN_URI = Downloads.Impl.COLUMN_URI;
Steve Howarda2709362010-07-02 17:12:48 -070089
90 /**
Steve Howard8651bd52010-08-03 12:35:32 -070091 * Internet Media Type of the downloaded file. If no value is provided upon creation, this will
92 * initially be null and will be filled in based on the server's response once the download has
93 * started.
Steve Howarda2709362010-07-02 17:12:48 -070094 *
95 * @see <a href="http://www.ietf.org/rfc/rfc1590.txt">RFC 1590, defining Media Types</a>
96 */
97 public final static String COLUMN_MEDIA_TYPE = "media_type";
98
99 /**
Steve Howard8651bd52010-08-03 12:35:32 -0700100 * Total size of the download in bytes. This will initially be -1 and will be filled in once
101 * the download starts.
Steve Howarda2709362010-07-02 17:12:48 -0700102 */
103 public final static String COLUMN_TOTAL_SIZE_BYTES = "total_size";
104
105 /**
106 * Uri where downloaded file will be stored. If a destination is supplied by client, that URI
Steve Howard8651bd52010-08-03 12:35:32 -0700107 * will be used here. Otherwise, the value will initially be null and will be filled in with a
108 * generated URI once the download has started.
Steve Howarda2709362010-07-02 17:12:48 -0700109 */
110 public final static String COLUMN_LOCAL_URI = "local_uri";
111
112 /**
Jeff Sharkey60cfad82016-01-05 17:30:57 -0700113 * Path to the downloaded file on disk.
114 * <p>
115 * Note that apps may not have filesystem permissions to directly access
116 * this path. Instead of trying to open this path directly, apps should use
117 * {@link ContentResolver#openFileDescriptor(Uri, String)} to gain access.
118 *
119 * @deprecated apps should transition to using
120 * {@link ContentResolver#openFileDescriptor(Uri, String)}
121 * instead.
Doug Zongkeree04af32010-10-08 13:42:16 -0700122 */
Jeff Sharkey60cfad82016-01-05 17:30:57 -0700123 @Deprecated
Doug Zongkeree04af32010-10-08 13:42:16 -0700124 public final static String COLUMN_LOCAL_FILENAME = "local_filename";
125
126 /**
Steve Howarda2709362010-07-02 17:12:48 -0700127 * Current status of the download, as one of the STATUS_* constants.
128 */
Vasu Norief7e33b2010-10-20 13:26:02 -0700129 public final static String COLUMN_STATUS = Downloads.Impl.COLUMN_STATUS;
Steve Howarda2709362010-07-02 17:12:48 -0700130
131 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700132 * Provides more detail on the status of the download. Its meaning depends on the value of
133 * {@link #COLUMN_STATUS}.
Steve Howarda2709362010-07-02 17:12:48 -0700134 *
Steve Howard3e8c1d32010-09-29 17:03:32 -0700135 * When {@link #COLUMN_STATUS} is {@link #STATUS_FAILED}, this indicates the type of error that
136 * occurred. If an HTTP error occurred, this will hold the HTTP status code as defined in RFC
137 * 2616. Otherwise, it will hold one of the ERROR_* constants.
138 *
139 * When {@link #COLUMN_STATUS} is {@link #STATUS_PAUSED}, this indicates why the download is
140 * paused. It will hold one of the PAUSED_* constants.
141 *
142 * If {@link #COLUMN_STATUS} is neither {@link #STATUS_FAILED} nor {@link #STATUS_PAUSED}, this
143 * column's value is undefined.
Steve Howarda2709362010-07-02 17:12:48 -0700144 *
145 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1.1">RFC 2616
146 * status codes</a>
147 */
Steve Howard3e8c1d32010-09-29 17:03:32 -0700148 public final static String COLUMN_REASON = "reason";
Steve Howarda2709362010-07-02 17:12:48 -0700149
150 /**
151 * Number of bytes download so far.
152 */
153 public final static String COLUMN_BYTES_DOWNLOADED_SO_FAR = "bytes_so_far";
154
155 /**
Steve Howardadcb6972010-07-12 17:09:25 -0700156 * Timestamp when the download was last modified, in {@link System#currentTimeMillis
Steve Howarda2709362010-07-02 17:12:48 -0700157 * System.currentTimeMillis()} (wall clock time in UTC).
158 */
Steve Howardadcb6972010-07-12 17:09:25 -0700159 public final static String COLUMN_LAST_MODIFIED_TIMESTAMP = "last_modified_timestamp";
Steve Howarda2709362010-07-02 17:12:48 -0700160
Vasu Nori216fa222010-10-12 23:08:13 -0700161 /**
162 * The URI to the corresponding entry in MediaProvider for this downloaded entry. It is
163 * used to delete the entries from MediaProvider database when it is deleted from the
164 * downloaded list.
165 */
Vasu Norief7e33b2010-10-20 13:26:02 -0700166 public static final String COLUMN_MEDIAPROVIDER_URI = Downloads.Impl.COLUMN_MEDIAPROVIDER_URI;
Steve Howarda2709362010-07-02 17:12:48 -0700167
168 /**
Jeff Sharkeyb180a652013-09-23 14:23:41 -0700169 * @hide
170 */
171 public final static String COLUMN_ALLOW_WRITE = Downloads.Impl.COLUMN_ALLOW_WRITE;
172
173 /**
Steve Howarda2709362010-07-02 17:12:48 -0700174 * Value of {@link #COLUMN_STATUS} when the download is waiting to start.
175 */
176 public final static int STATUS_PENDING = 1 << 0;
177
178 /**
179 * Value of {@link #COLUMN_STATUS} when the download is currently running.
180 */
181 public final static int STATUS_RUNNING = 1 << 1;
182
183 /**
184 * Value of {@link #COLUMN_STATUS} when the download is waiting to retry or resume.
185 */
186 public final static int STATUS_PAUSED = 1 << 2;
187
188 /**
189 * Value of {@link #COLUMN_STATUS} when the download has successfully completed.
190 */
191 public final static int STATUS_SUCCESSFUL = 1 << 3;
192
193 /**
194 * Value of {@link #COLUMN_STATUS} when the download has failed (and will not be retried).
195 */
196 public final static int STATUS_FAILED = 1 << 4;
197
Steve Howarda2709362010-07-02 17:12:48 -0700198 /**
199 * Value of COLUMN_ERROR_CODE when the download has completed with an error that doesn't fit
200 * under any other error code.
201 */
202 public final static int ERROR_UNKNOWN = 1000;
203
204 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700205 * Value of {@link #COLUMN_REASON} when a storage issue arises which doesn't fit under any
Steve Howarda2709362010-07-02 17:12:48 -0700206 * other error code. Use the more specific {@link #ERROR_INSUFFICIENT_SPACE} and
207 * {@link #ERROR_DEVICE_NOT_FOUND} when appropriate.
208 */
209 public final static int ERROR_FILE_ERROR = 1001;
210
211 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700212 * Value of {@link #COLUMN_REASON} when an HTTP code was received that download manager
Steve Howarda2709362010-07-02 17:12:48 -0700213 * can't handle.
214 */
215 public final static int ERROR_UNHANDLED_HTTP_CODE = 1002;
216
217 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700218 * Value of {@link #COLUMN_REASON} when an error receiving or processing data occurred at
Steve Howarda2709362010-07-02 17:12:48 -0700219 * the HTTP level.
220 */
221 public final static int ERROR_HTTP_DATA_ERROR = 1004;
222
223 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700224 * Value of {@link #COLUMN_REASON} when there were too many redirects.
Steve Howarda2709362010-07-02 17:12:48 -0700225 */
226 public final static int ERROR_TOO_MANY_REDIRECTS = 1005;
227
228 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700229 * Value of {@link #COLUMN_REASON} when there was insufficient storage space. Typically,
Steve Howarda2709362010-07-02 17:12:48 -0700230 * this is because the SD card is full.
231 */
232 public final static int ERROR_INSUFFICIENT_SPACE = 1006;
233
234 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700235 * Value of {@link #COLUMN_REASON} when no external storage device was found. Typically,
Steve Howarda2709362010-07-02 17:12:48 -0700236 * this is because the SD card is not mounted.
237 */
238 public final static int ERROR_DEVICE_NOT_FOUND = 1007;
239
Steve Howardb8e07a52010-07-21 14:53:21 -0700240 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700241 * Value of {@link #COLUMN_REASON} when some possibly transient error occurred but we can't
Steve Howard33bbd122010-08-02 17:51:29 -0700242 * resume the download.
243 */
244 public final static int ERROR_CANNOT_RESUME = 1008;
245
246 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700247 * Value of {@link #COLUMN_REASON} when the requested destination file already exists (the
Steve Howarda9e87c92010-09-16 12:02:03 -0700248 * download manager will not overwrite an existing file).
249 */
250 public final static int ERROR_FILE_ALREADY_EXISTS = 1009;
251
252 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700253 * Value of {@link #COLUMN_REASON} when the download has failed because of
254 * {@link NetworkPolicyManager} controls on the requesting application.
255 *
256 * @hide
257 */
258 public final static int ERROR_BLOCKED = 1010;
259
260 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700261 * Value of {@link #COLUMN_REASON} when the download is paused because some network error
262 * occurred and the download manager is waiting before retrying the request.
263 */
264 public final static int PAUSED_WAITING_TO_RETRY = 1;
265
266 /**
267 * Value of {@link #COLUMN_REASON} when the download is waiting for network connectivity to
268 * proceed.
269 */
270 public final static int PAUSED_WAITING_FOR_NETWORK = 2;
271
272 /**
273 * Value of {@link #COLUMN_REASON} when the download exceeds a size limit for downloads over
274 * the mobile network and the download manager is waiting for a Wi-Fi connection to proceed.
275 */
276 public final static int PAUSED_QUEUED_FOR_WIFI = 3;
277
278 /**
279 * Value of {@link #COLUMN_REASON} when the download is paused for some other reason.
280 */
281 public final static int PAUSED_UNKNOWN = 4;
282
283 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700284 * Broadcast intent action sent by the download manager when a download completes.
285 */
Jeff Sharkey32cd2fb2013-10-02 10:11:22 -0700286 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Steve Howardb8e07a52010-07-21 14:53:21 -0700287 public final static String ACTION_DOWNLOAD_COMPLETE = "android.intent.action.DOWNLOAD_COMPLETE";
288
289 /**
Steve Howard610c4352010-09-30 18:30:04 -0700290 * Broadcast intent action sent by the download manager when the user clicks on a running
291 * download, either from a system notification or from the downloads UI.
Steve Howardb8e07a52010-07-21 14:53:21 -0700292 */
Jeff Sharkey32cd2fb2013-10-02 10:11:22 -0700293 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Steve Howardb8e07a52010-07-21 14:53:21 -0700294 public final static String ACTION_NOTIFICATION_CLICKED =
295 "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED";
296
297 /**
Steve Howarde78fc182010-09-24 14:59:36 -0700298 * Intent action to launch an activity to display all downloads.
299 */
Jeff Sharkey32cd2fb2013-10-02 10:11:22 -0700300 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
Steve Howarde78fc182010-09-24 14:59:36 -0700301 public final static String ACTION_VIEW_DOWNLOADS = "android.intent.action.VIEW_DOWNLOADS";
302
303 /**
Vasu Norie5f92242011-01-24 16:12:20 -0800304 * Intent extra included with {@link #ACTION_VIEW_DOWNLOADS} to start DownloadApp in
305 * sort-by-size mode.
306 */
307 public final static String INTENT_EXTRAS_SORT_BY_SIZE =
308 "android.app.DownloadManager.extra_sortBySize";
309
310 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700311 * Intent extra included with {@link #ACTION_DOWNLOAD_COMPLETE} intents, indicating the ID (as a
312 * long) of the download that just completed.
313 */
314 public static final String EXTRA_DOWNLOAD_ID = "extra_download_id";
Steve Howarda2709362010-07-02 17:12:48 -0700315
Vasu Nori71b8c232010-10-27 15:22:19 -0700316 /**
317 * When clicks on multiple notifications are received, the following
318 * provides an array of download ids corresponding to the download notification that was
319 * clicked. It can be retrieved by the receiver of this
320 * Intent using {@link android.content.Intent#getLongArrayExtra(String)}.
321 */
322 public static final String EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS = "extra_click_download_ids";
323
Vasu Norie16c43b2010-11-06 18:48:08 -0700324 /**
325 * columns to request from DownloadProvider.
326 * @hide
327 */
328 public static final String[] UNDERLYING_COLUMNS = new String[] {
Steve Howarda2709362010-07-02 17:12:48 -0700329 Downloads.Impl._ID,
Vasu Norie69924f2010-11-15 13:10:11 -0800330 Downloads.Impl._DATA + " AS " + COLUMN_LOCAL_FILENAME,
Vasu Nori216fa222010-10-12 23:08:13 -0700331 Downloads.Impl.COLUMN_MEDIAPROVIDER_URI,
Vasu Nori5be894e2010-11-02 21:55:30 -0700332 Downloads.Impl.COLUMN_DESTINATION,
Vasu Norief7e33b2010-10-20 13:26:02 -0700333 Downloads.Impl.COLUMN_TITLE,
334 Downloads.Impl.COLUMN_DESCRIPTION,
335 Downloads.Impl.COLUMN_URI,
Vasu Norief7e33b2010-10-20 13:26:02 -0700336 Downloads.Impl.COLUMN_STATUS,
Steve Howarda9e87c92010-09-16 12:02:03 -0700337 Downloads.Impl.COLUMN_FILE_NAME_HINT,
Vasu Norie16c43b2010-11-06 18:48:08 -0700338 Downloads.Impl.COLUMN_MIME_TYPE + " AS " + COLUMN_MEDIA_TYPE,
339 Downloads.Impl.COLUMN_TOTAL_BYTES + " AS " + COLUMN_TOTAL_SIZE_BYTES,
340 Downloads.Impl.COLUMN_LAST_MODIFICATION + " AS " + COLUMN_LAST_MODIFIED_TIMESTAMP,
341 Downloads.Impl.COLUMN_CURRENT_BYTES + " AS " + COLUMN_BYTES_DOWNLOADED_SO_FAR,
Jeff Sharkeyb180a652013-09-23 14:23:41 -0700342 Downloads.Impl.COLUMN_ALLOW_WRITE,
Vasu Norie16c43b2010-11-06 18:48:08 -0700343 /* add the following 'computed' columns to the cursor.
344 * they are not 'returned' by the database, but their inclusion
345 * eliminates need to have lot of methods in CursorTranslator
346 */
347 "'placeholder' AS " + COLUMN_LOCAL_URI,
348 "'placeholder' AS " + COLUMN_REASON
Steve Howarda2709362010-07-02 17:12:48 -0700349 };
350
Steve Howarda2709362010-07-02 17:12:48 -0700351 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700352 * This class contains all the information necessary to request a new download. The URI is the
Steve Howarda2709362010-07-02 17:12:48 -0700353 * only required parameter.
Steve Howard4f564cd2010-09-22 15:57:25 -0700354 *
355 * Note that the default download destination is a shared volume where the system might delete
356 * your file if it needs to reclaim space for system use. If this is a problem, use a location
357 * on external storage (see {@link #setDestinationUri(Uri)}.
Steve Howarda2709362010-07-02 17:12:48 -0700358 */
359 public static class Request {
360 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700361 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
362 * {@link ConnectivityManager#TYPE_MOBILE}.
363 */
364 public static final int NETWORK_MOBILE = 1 << 0;
Steve Howarda2709362010-07-02 17:12:48 -0700365
Steve Howardb8e07a52010-07-21 14:53:21 -0700366 /**
367 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
368 * {@link ConnectivityManager#TYPE_WIFI}.
369 */
370 public static final int NETWORK_WIFI = 1 << 1;
371
HÃ¥kan3 Johansson011238b2012-02-08 21:13:35 +0100372 /**
373 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
374 * {@link ConnectivityManager#TYPE_BLUETOOTH}.
375 * @hide
376 */
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600377 @Deprecated
HÃ¥kan3 Johansson011238b2012-02-08 21:13:35 +0100378 public static final int NETWORK_BLUETOOTH = 1 << 2;
379
Steve Howardb8e07a52010-07-21 14:53:21 -0700380 private Uri mUri;
381 private Uri mDestinationUri;
Steve Howard4f564cd2010-09-22 15:57:25 -0700382 private List<Pair<String, String>> mRequestHeaders = new ArrayList<Pair<String, String>>();
383 private CharSequence mTitle;
384 private CharSequence mDescription;
Steve Howard4f564cd2010-09-22 15:57:25 -0700385 private String mMimeType;
Steve Howardb8e07a52010-07-21 14:53:21 -0700386 private int mAllowedNetworkTypes = ~0; // default to all network types allowed
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700387 private boolean mRoamingAllowed = true;
388 private boolean mMeteredAllowed = true;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600389 private int mFlags = 0;
Steve Howard90fb15a2010-09-09 16:13:41 -0700390 private boolean mIsVisibleInDownloadsUi = true;
Vasu Nori5be894e2010-11-02 21:55:30 -0700391 private boolean mScannable = false;
Vasu Norif83e6e42010-12-13 16:28:31 -0800392 private boolean mUseSystemCache = false;
Vasu Nori1cde3fb2010-11-05 11:02:52 -0700393 /** if a file is designated as a MediaScanner scannable file, the following value is
394 * stored in the database column {@link Downloads.Impl#COLUMN_MEDIA_SCANNED}.
395 */
396 private static final int SCANNABLE_VALUE_YES = 0;
397 // value of 1 is stored in the above column by DownloadProvider after it is scanned by
398 // MediaScanner
399 /** if a file is designated as a file that should not be scanned by MediaScanner,
400 * the following value is stored in the database column
401 * {@link Downloads.Impl#COLUMN_MEDIA_SCANNED}.
402 */
403 private static final int SCANNABLE_VALUE_NO = 2;
Steve Howarda2709362010-07-02 17:12:48 -0700404
405 /**
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700406 * This download is visible but only shows in the notifications
407 * while it's in progress.
408 */
409 public static final int VISIBILITY_VISIBLE = 0;
410
411 /**
412 * This download is visible and shows in the notifications while
413 * in progress and after completion.
414 */
415 public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED = 1;
416
417 /**
418 * This download doesn't show in the UI or in the notifications.
419 */
420 public static final int VISIBILITY_HIDDEN = 2;
421
Vasu Norif9e85232011-02-10 14:59:54 -0800422 /**
423 * This download shows in the notifications after completion ONLY.
424 * It is usuable only with
Vasu Nori37281302011-03-07 11:25:01 -0800425 * {@link DownloadManager#addCompletedDownload(String, String,
426 * boolean, String, String, long, boolean)}.
Vasu Norif9e85232011-02-10 14:59:54 -0800427 */
428 public static final int VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION = 3;
429
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700430 /** can take any of the following values: {@link #VISIBILITY_HIDDEN}
Vasu Norif9e85232011-02-10 14:59:54 -0800431 * {@link #VISIBILITY_VISIBLE_NOTIFY_COMPLETED}, {@link #VISIBILITY_VISIBLE},
432 * {@link #VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION}
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700433 */
434 private int mNotificationVisibility = VISIBILITY_VISIBLE;
435
436 /**
Alex Klyubin66629bc2015-06-11 14:34:44 -0700437 * @param uri the HTTP or HTTPS URI to download.
Steve Howarda2709362010-07-02 17:12:48 -0700438 */
439 public Request(Uri uri) {
440 if (uri == null) {
441 throw new NullPointerException();
442 }
443 String scheme = uri.getScheme();
Paul Westbrook86a60192010-09-15 12:55:49 -0700444 if (scheme == null || (!scheme.equals("http") && !scheme.equals("https"))) {
445 throw new IllegalArgumentException("Can only download HTTP/HTTPS URIs: " + uri);
Steve Howarda2709362010-07-02 17:12:48 -0700446 }
447 mUri = uri;
448 }
449
Vasu Noric0e50752011-01-20 17:57:54 -0800450 Request(String uriString) {
451 mUri = Uri.parse(uriString);
452 }
453
Steve Howarda2709362010-07-02 17:12:48 -0700454 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700455 * Set the local destination for the downloaded file. Must be a file URI to a path on
Steve Howarda2709362010-07-02 17:12:48 -0700456 * external storage, and the calling application must have the WRITE_EXTERNAL_STORAGE
457 * permission.
Vasu Nori5be894e2010-11-02 21:55:30 -0700458 * <p>
459 * The downloaded file is not scanned by MediaScanner.
460 * But it can be made scannable by calling {@link #allowScanningByMediaScanner()}.
461 * <p>
Steve Howard4f564cd2010-09-22 15:57:25 -0700462 * By default, downloads are saved to a generated filename in the shared download cache and
463 * may be deleted by the system at any time to reclaim space.
Steve Howarda2709362010-07-02 17:12:48 -0700464 *
465 * @return this object
466 */
467 public Request setDestinationUri(Uri uri) {
468 mDestinationUri = uri;
469 return this;
470 }
471
472 /**
Vasu Norif83e6e42010-12-13 16:28:31 -0800473 * Set the local destination for the downloaded file to the system cache dir (/cache).
474 * This is only available to System apps with the permission
475 * {@link android.Manifest.permission#ACCESS_CACHE_FILESYSTEM}.
476 * <p>
477 * The downloaded file is not scanned by MediaScanner.
478 * But it can be made scannable by calling {@link #allowScanningByMediaScanner()}.
479 * <p>
480 * Files downloaded to /cache may be deleted by the system at any time to reclaim space.
481 *
482 * @return this object
483 * @hide
484 */
485 public Request setDestinationToSystemCache() {
486 mUseSystemCache = true;
487 return this;
488 }
489
490 /**
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700491 * Set the local destination for the downloaded file to a path within
492 * the application's external files directory (as returned by
493 * {@link Context#getExternalFilesDir(String)}.
Vasu Nori5be894e2010-11-02 21:55:30 -0700494 * <p>
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700495 * The downloaded file is not scanned by MediaScanner. But it can be
496 * made scannable by calling {@link #allowScanningByMediaScanner()}.
Steve Howard4f564cd2010-09-22 15:57:25 -0700497 *
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700498 * @param context the {@link Context} to use in determining the external
499 * files directory
500 * @param dirType the directory type to pass to
501 * {@link Context#getExternalFilesDir(String)}
502 * @param subPath the path within the external directory, including the
503 * destination filename
Steve Howard4f564cd2010-09-22 15:57:25 -0700504 * @return this object
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700505 * @throws IllegalStateException If the external storage directory
506 * cannot be found or created.
Steve Howard4f564cd2010-09-22 15:57:25 -0700507 */
508 public Request setDestinationInExternalFilesDir(Context context, String dirType,
509 String subPath) {
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700510 final File file = context.getExternalFilesDir(dirType);
511 if (file == null) {
512 throw new IllegalStateException("Failed to get external storage files directory");
513 } else if (file.exists()) {
514 if (!file.isDirectory()) {
515 throw new IllegalStateException(file.getAbsolutePath() +
516 " already exists and is not a directory");
517 }
518 } else {
519 if (!file.mkdirs()) {
520 throw new IllegalStateException("Unable to create directory: "+
521 file.getAbsolutePath());
522 }
523 }
524 setDestinationFromBase(file, subPath);
Steve Howard4f564cd2010-09-22 15:57:25 -0700525 return this;
526 }
527
528 /**
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700529 * Set the local destination for the downloaded file to a path within
530 * the public external storage directory (as returned by
531 * {@link Environment#getExternalStoragePublicDirectory(String)}).
532 * <p>
533 * The downloaded file is not scanned by MediaScanner. But it can be
534 * made scannable by calling {@link #allowScanningByMediaScanner()}.
Steve Howard4f564cd2010-09-22 15:57:25 -0700535 *
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700536 * @param dirType the directory type to pass to {@link Environment#getExternalStoragePublicDirectory(String)}
537 * @param subPath the path within the external directory, including the
538 * destination filename
Steve Howard4f564cd2010-09-22 15:57:25 -0700539 * @return this object
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700540 * @throws IllegalStateException If the external storage directory
541 * cannot be found or created.
Steve Howard4f564cd2010-09-22 15:57:25 -0700542 */
543 public Request setDestinationInExternalPublicDir(String dirType, String subPath) {
Vasu Nori6916b032010-12-19 20:31:00 -0800544 File file = Environment.getExternalStoragePublicDirectory(dirType);
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700545 if (file == null) {
546 throw new IllegalStateException("Failed to get external storage public directory");
547 } else if (file.exists()) {
Vasu Nori6916b032010-12-19 20:31:00 -0800548 if (!file.isDirectory()) {
549 throw new IllegalStateException(file.getAbsolutePath() +
550 " already exists and is not a directory");
551 }
552 } else {
Roger Chen1740ada2012-12-17 13:31:17 +0800553 if (!file.mkdirs()) {
Vasu Nori6916b032010-12-19 20:31:00 -0800554 throw new IllegalStateException("Unable to create directory: "+
555 file.getAbsolutePath());
556 }
557 }
558 setDestinationFromBase(file, subPath);
Steve Howard4f564cd2010-09-22 15:57:25 -0700559 return this;
560 }
561
562 private void setDestinationFromBase(File base, String subPath) {
563 if (subPath == null) {
564 throw new NullPointerException("subPath cannot be null");
565 }
566 mDestinationUri = Uri.withAppendedPath(Uri.fromFile(base), subPath);
567 }
568
569 /**
Vasu Nori5be894e2010-11-02 21:55:30 -0700570 * If the file to be downloaded is to be scanned by MediaScanner, this method
571 * should be called before {@link DownloadManager#enqueue(Request)} is called.
572 */
573 public void allowScanningByMediaScanner() {
574 mScannable = true;
575 }
576
577 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700578 * Add an HTTP header to be included with the download request. The header will be added to
579 * the end of the list.
Steve Howarda2709362010-07-02 17:12:48 -0700580 * @param header HTTP header name
581 * @param value header value
582 * @return this object
Steve Howard4f564cd2010-09-22 15:57:25 -0700583 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2">HTTP/1.1
584 * Message Headers</a>
Steve Howarda2709362010-07-02 17:12:48 -0700585 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700586 public Request addRequestHeader(String header, String value) {
587 if (header == null) {
588 throw new NullPointerException("header cannot be null");
589 }
590 if (header.contains(":")) {
591 throw new IllegalArgumentException("header may not contain ':'");
592 }
593 if (value == null) {
594 value = "";
595 }
596 mRequestHeaders.add(Pair.create(header, value));
Steve Howarda2709362010-07-02 17:12:48 -0700597 return this;
598 }
599
600 /**
Steve Howard610c4352010-09-30 18:30:04 -0700601 * Set the title of this download, to be displayed in notifications (if enabled). If no
602 * title is given, a default one will be assigned based on the download filename, once the
603 * download starts.
Steve Howarda2709362010-07-02 17:12:48 -0700604 * @return this object
605 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700606 public Request setTitle(CharSequence title) {
Steve Howarda2709362010-07-02 17:12:48 -0700607 mTitle = title;
608 return this;
609 }
610
611 /**
612 * Set a description of this download, to be displayed in notifications (if enabled)
613 * @return this object
614 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700615 public Request setDescription(CharSequence description) {
Steve Howarda2709362010-07-02 17:12:48 -0700616 mDescription = description;
617 return this;
618 }
619
620 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700621 * Set the MIME content type of this download. This will override the content type declared
Steve Howarda2709362010-07-02 17:12:48 -0700622 * in the server's response.
Steve Howard4f564cd2010-09-22 15:57:25 -0700623 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7">HTTP/1.1
624 * Media Types</a>
Steve Howarda2709362010-07-02 17:12:48 -0700625 * @return this object
626 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700627 public Request setMimeType(String mimeType) {
628 mMimeType = mimeType;
Steve Howarda2709362010-07-02 17:12:48 -0700629 return this;
630 }
631
632 /**
Steve Howard8e15afe2010-07-28 17:12:40 -0700633 * Control whether a system notification is posted by the download manager while this
634 * download is running. If enabled, the download manager posts notifications about downloads
635 * through the system {@link android.app.NotificationManager}. By default, a notification is
636 * shown.
Steve Howarda2709362010-07-02 17:12:48 -0700637 *
Steve Howard8e15afe2010-07-28 17:12:40 -0700638 * If set to false, this requires the permission
639 * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
640 *
641 * @param show whether the download manager should show a notification for this download.
Steve Howarda2709362010-07-02 17:12:48 -0700642 * @return this object
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700643 * @deprecated use {@link #setNotificationVisibility(int)}
Steve Howarda2709362010-07-02 17:12:48 -0700644 */
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700645 @Deprecated
Steve Howard8e15afe2010-07-28 17:12:40 -0700646 public Request setShowRunningNotification(boolean show) {
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700647 return (show) ? setNotificationVisibility(VISIBILITY_VISIBLE) :
648 setNotificationVisibility(VISIBILITY_HIDDEN);
649 }
650
651 /**
652 * Control whether a system notification is posted by the download manager while this
653 * download is running or when it is completed.
654 * If enabled, the download manager posts notifications about downloads
655 * through the system {@link android.app.NotificationManager}.
656 * By default, a notification is shown only when the download is in progress.
657 *<p>
658 * It can take the following values: {@link #VISIBILITY_HIDDEN},
659 * {@link #VISIBILITY_VISIBLE},
660 * {@link #VISIBILITY_VISIBLE_NOTIFY_COMPLETED}.
661 *<p>
662 * If set to {@link #VISIBILITY_HIDDEN}, this requires the permission
663 * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
664 *
665 * @param visibility the visibility setting value
666 * @return this object
667 */
668 public Request setNotificationVisibility(int visibility) {
669 mNotificationVisibility = visibility;
Steve Howarda2709362010-07-02 17:12:48 -0700670 return this;
671 }
672
Steve Howardb8e07a52010-07-21 14:53:21 -0700673 /**
Jeff Sharkey792e0912012-04-16 11:52:18 -0700674 * Restrict the types of networks over which this download may proceed.
675 * By default, all network types are allowed. Consider using
676 * {@link #setAllowedOverMetered(boolean)} instead, since it's more
677 * flexible.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600678 * <p>
679 * As of {@link android.os.Build.VERSION_CODES#N}, setting only the
680 * {@link #NETWORK_WIFI} flag here is equivalent to calling
681 * {@link #setAllowedOverMetered(boolean)} with {@code false}.
Jeff Sharkey792e0912012-04-16 11:52:18 -0700682 *
Steve Howardb8e07a52010-07-21 14:53:21 -0700683 * @param flags any combination of the NETWORK_* bit flags.
684 * @return this object
685 */
Steve Howarda2709362010-07-02 17:12:48 -0700686 public Request setAllowedNetworkTypes(int flags) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700687 mAllowedNetworkTypes = flags;
688 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700689 }
690
Steve Howardb8e07a52010-07-21 14:53:21 -0700691 /**
692 * Set whether this download may proceed over a roaming connection. By default, roaming is
693 * allowed.
694 * @param allowed whether to allow a roaming connection to be used
695 * @return this object
696 */
Steve Howarda2709362010-07-02 17:12:48 -0700697 public Request setAllowedOverRoaming(boolean allowed) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700698 mRoamingAllowed = allowed;
699 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700700 }
701
702 /**
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700703 * Set whether this download may proceed over a metered network
704 * connection. By default, metered networks are allowed.
705 *
706 * @see ConnectivityManager#isActiveNetworkMetered()
707 */
708 public Request setAllowedOverMetered(boolean allow) {
709 mMeteredAllowed = allow;
710 return this;
711 }
712
713 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600714 * Specify that to run this download, the device needs to be plugged in.
715 * This defaults to false.
716 *
717 * @param requiresCharging Whether or not the device is plugged in.
718 * @see android.app.job.JobInfo.Builder#setRequiresCharging(boolean)
719 */
720 public Request setRequiresCharging(boolean requiresCharging) {
721 if (requiresCharging) {
722 mFlags |= Downloads.Impl.FLAG_REQUIRES_CHARGING;
723 } else {
724 mFlags &= ~Downloads.Impl.FLAG_REQUIRES_CHARGING;
725 }
726 return this;
727 }
728
729 /**
730 * Specify that to run, the download needs the device to be in idle
731 * mode. This defaults to false.
732 * <p>
733 * Idle mode is a loose definition provided by the system, which means
734 * that the device is not in use, and has not been in use for some time.
735 *
736 * @param requiresDeviceIdle Whether or not the device need be within an
737 * idle maintenance window.
738 * @see android.app.job.JobInfo.Builder#setRequiresDeviceIdle(boolean)
739 */
740 public Request setRequiresDeviceIdle(boolean requiresDeviceIdle) {
741 if (requiresDeviceIdle) {
742 mFlags |= Downloads.Impl.FLAG_REQUIRES_DEVICE_IDLE;
743 } else {
744 mFlags &= ~Downloads.Impl.FLAG_REQUIRES_DEVICE_IDLE;
745 }
746 return this;
747 }
748
749 /**
Steve Howard90fb15a2010-09-09 16:13:41 -0700750 * Set whether this download should be displayed in the system's Downloads UI. True by
751 * default.
752 * @param isVisible whether to display this download in the Downloads UI
753 * @return this object
754 */
755 public Request setVisibleInDownloadsUi(boolean isVisible) {
756 mIsVisibleInDownloadsUi = isVisible;
757 return this;
758 }
759
760 /**
Steve Howarda2709362010-07-02 17:12:48 -0700761 * @return ContentValues to be passed to DownloadProvider.insert()
762 */
Steve Howardb8e07a52010-07-21 14:53:21 -0700763 ContentValues toContentValues(String packageName) {
Steve Howarda2709362010-07-02 17:12:48 -0700764 ContentValues values = new ContentValues();
765 assert mUri != null;
Vasu Norief7e33b2010-10-20 13:26:02 -0700766 values.put(Downloads.Impl.COLUMN_URI, mUri.toString());
Steve Howardb8e07a52010-07-21 14:53:21 -0700767 values.put(Downloads.Impl.COLUMN_IS_PUBLIC_API, true);
Vasu Norief7e33b2010-10-20 13:26:02 -0700768 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE, packageName);
Steve Howarda2709362010-07-02 17:12:48 -0700769
770 if (mDestinationUri != null) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700771 values.put(Downloads.Impl.COLUMN_DESTINATION, Downloads.Impl.DESTINATION_FILE_URI);
772 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, mDestinationUri.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700773 } else {
Vasu Norief7e33b2010-10-20 13:26:02 -0700774 values.put(Downloads.Impl.COLUMN_DESTINATION,
Vasu Norif83e6e42010-12-13 16:28:31 -0800775 (this.mUseSystemCache) ?
776 Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION :
777 Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE);
Steve Howarda2709362010-07-02 17:12:48 -0700778 }
Vasu Nori5be894e2010-11-02 21:55:30 -0700779 // is the file supposed to be media-scannable?
Vasu Nori1cde3fb2010-11-05 11:02:52 -0700780 values.put(Downloads.Impl.COLUMN_MEDIA_SCANNED, (mScannable) ? SCANNABLE_VALUE_YES :
781 SCANNABLE_VALUE_NO);
Steve Howarda2709362010-07-02 17:12:48 -0700782
783 if (!mRequestHeaders.isEmpty()) {
Steve Howardea9147d2010-07-13 19:02:45 -0700784 encodeHttpHeaders(values);
Steve Howarda2709362010-07-02 17:12:48 -0700785 }
786
Vasu Norief7e33b2010-10-20 13:26:02 -0700787 putIfNonNull(values, Downloads.Impl.COLUMN_TITLE, mTitle);
788 putIfNonNull(values, Downloads.Impl.COLUMN_DESCRIPTION, mDescription);
789 putIfNonNull(values, Downloads.Impl.COLUMN_MIME_TYPE, mMimeType);
Steve Howarda2709362010-07-02 17:12:48 -0700790
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700791 values.put(Downloads.Impl.COLUMN_VISIBILITY, mNotificationVisibility);
Steve Howardb8e07a52010-07-21 14:53:21 -0700792 values.put(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES, mAllowedNetworkTypes);
793 values.put(Downloads.Impl.COLUMN_ALLOW_ROAMING, mRoamingAllowed);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700794 values.put(Downloads.Impl.COLUMN_ALLOW_METERED, mMeteredAllowed);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600795 values.put(Downloads.Impl.COLUMN_FLAGS, mFlags);
Steve Howard90fb15a2010-09-09 16:13:41 -0700796 values.put(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, mIsVisibleInDownloadsUi);
Steve Howardb8e07a52010-07-21 14:53:21 -0700797
Steve Howarda2709362010-07-02 17:12:48 -0700798 return values;
799 }
800
Steve Howardea9147d2010-07-13 19:02:45 -0700801 private void encodeHttpHeaders(ContentValues values) {
802 int index = 0;
Steve Howard4f564cd2010-09-22 15:57:25 -0700803 for (Pair<String, String> header : mRequestHeaders) {
804 String headerString = header.first + ": " + header.second;
Steve Howardea9147d2010-07-13 19:02:45 -0700805 values.put(Downloads.Impl.RequestHeaders.INSERT_KEY_PREFIX + index, headerString);
806 index++;
807 }
808 }
809
Steve Howard4f564cd2010-09-22 15:57:25 -0700810 private void putIfNonNull(ContentValues contentValues, String key, Object value) {
Steve Howarda2709362010-07-02 17:12:48 -0700811 if (value != null) {
Steve Howard4f564cd2010-09-22 15:57:25 -0700812 contentValues.put(key, value.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700813 }
814 }
815 }
816
817 /**
818 * This class may be used to filter download manager queries.
819 */
820 public static class Query {
Steve Howardf054e192010-09-01 18:26:26 -0700821 /**
822 * Constant for use with {@link #orderBy}
823 * @hide
824 */
825 public static final int ORDER_ASCENDING = 1;
826
827 /**
828 * Constant for use with {@link #orderBy}
829 * @hide
830 */
831 public static final int ORDER_DESCENDING = 2;
832
Steve Howard64c48b82010-10-07 17:53:52 -0700833 private long[] mIds = null;
Steve Howarda2709362010-07-02 17:12:48 -0700834 private Integer mStatusFlags = null;
Ben Lince763d82016-05-02 16:45:45 -0700835 private String mFilterString = null;
Vasu Norief7e33b2010-10-20 13:26:02 -0700836 private String mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
Steve Howardf054e192010-09-01 18:26:26 -0700837 private int mOrderDirection = ORDER_DESCENDING;
Steve Howard90fb15a2010-09-09 16:13:41 -0700838 private boolean mOnlyIncludeVisibleInDownloadsUi = false;
Steve Howarda2709362010-07-02 17:12:48 -0700839
840 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700841 * Include only the downloads with the given IDs.
Steve Howarda2709362010-07-02 17:12:48 -0700842 * @return this object
843 */
Steve Howard64c48b82010-10-07 17:53:52 -0700844 public Query setFilterById(long... ids) {
845 mIds = ids;
Steve Howarda2709362010-07-02 17:12:48 -0700846 return this;
847 }
848
849 /**
Ben Lince763d82016-05-02 16:45:45 -0700850 *
851 * Include only the downloads that contains the given string in its name.
852 * @return this object
853 * @hide
854 */
855 public Query setFilterByString(@Nullable String filter) {
856 mFilterString = filter;
857 return this;
858 }
859
860 /**
Steve Howarda2709362010-07-02 17:12:48 -0700861 * Include only downloads with status matching any the given status flags.
862 * @param flags any combination of the STATUS_* bit flags
863 * @return this object
864 */
865 public Query setFilterByStatus(int flags) {
866 mStatusFlags = flags;
867 return this;
868 }
869
870 /**
Steve Howard90fb15a2010-09-09 16:13:41 -0700871 * Controls whether this query includes downloads not visible in the system's Downloads UI.
872 * @param value if true, this query will only include downloads that should be displayed in
873 * the system's Downloads UI; if false (the default), this query will include
874 * both visible and invisible downloads.
875 * @return this object
876 * @hide
877 */
878 public Query setOnlyIncludeVisibleInDownloadsUi(boolean value) {
879 mOnlyIncludeVisibleInDownloadsUi = value;
880 return this;
881 }
882
883 /**
Steve Howardf054e192010-09-01 18:26:26 -0700884 * Change the sort order of the returned Cursor.
885 *
886 * @param column one of the COLUMN_* constants; currently, only
887 * {@link #COLUMN_LAST_MODIFIED_TIMESTAMP} and {@link #COLUMN_TOTAL_SIZE_BYTES} are
888 * supported.
889 * @param direction either {@link #ORDER_ASCENDING} or {@link #ORDER_DESCENDING}
890 * @return this object
891 * @hide
892 */
893 public Query orderBy(String column, int direction) {
894 if (direction != ORDER_ASCENDING && direction != ORDER_DESCENDING) {
895 throw new IllegalArgumentException("Invalid direction: " + direction);
896 }
897
898 if (column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP)) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700899 mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
Steve Howardf054e192010-09-01 18:26:26 -0700900 } else if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700901 mOrderByColumn = Downloads.Impl.COLUMN_TOTAL_BYTES;
Steve Howardf054e192010-09-01 18:26:26 -0700902 } else {
903 throw new IllegalArgumentException("Cannot order by " + column);
904 }
905 mOrderDirection = direction;
906 return this;
907 }
908
909 /**
Steve Howarda2709362010-07-02 17:12:48 -0700910 * Run this query using the given ContentResolver.
911 * @param projection the projection to pass to ContentResolver.query()
912 * @return the Cursor returned by ContentResolver.query()
913 */
Steve Howardeca77fc2010-09-12 18:49:08 -0700914 Cursor runQuery(ContentResolver resolver, String[] projection, Uri baseUri) {
915 Uri uri = baseUri;
Steve Howard90fb15a2010-09-09 16:13:41 -0700916 List<String> selectionParts = new ArrayList<String>();
Steve Howard64c48b82010-10-07 17:53:52 -0700917 String[] selectionArgs = null;
Steve Howarda2709362010-07-02 17:12:48 -0700918
Ben Lince763d82016-05-02 16:45:45 -0700919 int whereArgsCount = (mIds == null) ? 0 : mIds.length;
920 whereArgsCount = (mFilterString == null) ? whereArgsCount : whereArgsCount + 1;
921 selectionArgs = new String[whereArgsCount];
922
923 if (whereArgsCount > 0) {
924 if (mIds != null) {
925 selectionParts.add(getWhereClauseForIds(mIds));
926 getWhereArgsForIds(mIds, selectionArgs);
927 }
928
929 if (mFilterString != null) {
930 selectionParts.add(Downloads.Impl.COLUMN_TITLE + " LIKE ?");
931 selectionArgs[selectionArgs.length - 1] = "%" + mFilterString + "%";
932 }
Steve Howarda2709362010-07-02 17:12:48 -0700933 }
934
935 if (mStatusFlags != null) {
936 List<String> parts = new ArrayList<String>();
937 if ((mStatusFlags & STATUS_PENDING) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700938 parts.add(statusClause("=", Downloads.Impl.STATUS_PENDING));
Steve Howarda2709362010-07-02 17:12:48 -0700939 }
940 if ((mStatusFlags & STATUS_RUNNING) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700941 parts.add(statusClause("=", Downloads.Impl.STATUS_RUNNING));
Steve Howarda2709362010-07-02 17:12:48 -0700942 }
943 if ((mStatusFlags & STATUS_PAUSED) != 0) {
Steve Howard3e8c1d32010-09-29 17:03:32 -0700944 parts.add(statusClause("=", Downloads.Impl.STATUS_PAUSED_BY_APP));
945 parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_TO_RETRY));
946 parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_FOR_NETWORK));
947 parts.add(statusClause("=", Downloads.Impl.STATUS_QUEUED_FOR_WIFI));
Steve Howarda2709362010-07-02 17:12:48 -0700948 }
949 if ((mStatusFlags & STATUS_SUCCESSFUL) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700950 parts.add(statusClause("=", Downloads.Impl.STATUS_SUCCESS));
Steve Howarda2709362010-07-02 17:12:48 -0700951 }
952 if ((mStatusFlags & STATUS_FAILED) != 0) {
953 parts.add("(" + statusClause(">=", 400)
954 + " AND " + statusClause("<", 600) + ")");
955 }
Steve Howard90fb15a2010-09-09 16:13:41 -0700956 selectionParts.add(joinStrings(" OR ", parts));
Steve Howarda2709362010-07-02 17:12:48 -0700957 }
Steve Howardf054e192010-09-01 18:26:26 -0700958
Steve Howard90fb15a2010-09-09 16:13:41 -0700959 if (mOnlyIncludeVisibleInDownloadsUi) {
960 selectionParts.add(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI + " != '0'");
961 }
962
Vasu Nori216fa222010-10-12 23:08:13 -0700963 // only return rows which are not marked 'deleted = 1'
964 selectionParts.add(Downloads.Impl.COLUMN_DELETED + " != '1'");
965
Steve Howard90fb15a2010-09-09 16:13:41 -0700966 String selection = joinStrings(" AND ", selectionParts);
Steve Howardf054e192010-09-01 18:26:26 -0700967 String orderDirection = (mOrderDirection == ORDER_ASCENDING ? "ASC" : "DESC");
968 String orderBy = mOrderByColumn + " " + orderDirection;
969
Steve Howard64c48b82010-10-07 17:53:52 -0700970 return resolver.query(uri, projection, selection, selectionArgs, orderBy);
Steve Howarda2709362010-07-02 17:12:48 -0700971 }
972
973 private String joinStrings(String joiner, Iterable<String> parts) {
974 StringBuilder builder = new StringBuilder();
975 boolean first = true;
976 for (String part : parts) {
977 if (!first) {
978 builder.append(joiner);
979 }
980 builder.append(part);
981 first = false;
982 }
983 return builder.toString();
984 }
985
986 private String statusClause(String operator, int value) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700987 return Downloads.Impl.COLUMN_STATUS + operator + "'" + value + "'";
Steve Howarda2709362010-07-02 17:12:48 -0700988 }
989 }
990
Jeff Sharkey60cfad82016-01-05 17:30:57 -0700991 private final ContentResolver mResolver;
992 private final String mPackageName;
Jeff Sharkey60cfad82016-01-05 17:30:57 -0700993
Steve Howardeca77fc2010-09-12 18:49:08 -0700994 private Uri mBaseUri = Downloads.Impl.CONTENT_URI;
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -0700995 private boolean mAccessFilename;
Steve Howarda2709362010-07-02 17:12:48 -0700996
997 /**
998 * @hide
999 */
Jeff Sharkey60cfad82016-01-05 17:30:57 -07001000 public DownloadManager(Context context) {
1001 mResolver = context.getContentResolver();
1002 mPackageName = context.getPackageName();
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001003
1004 // Callers can access filename columns when targeting old platform
1005 // versions; otherwise we throw telling them it's deprecated.
1006 mAccessFilename = context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N;
Steve Howarda2709362010-07-02 17:12:48 -07001007 }
1008
1009 /**
Steve Howardeca77fc2010-09-12 18:49:08 -07001010 * Makes this object access the download provider through /all_downloads URIs rather than
1011 * /my_downloads URIs, for clients that have permission to do so.
1012 * @hide
1013 */
1014 public void setAccessAllDownloads(boolean accessAllDownloads) {
1015 if (accessAllDownloads) {
1016 mBaseUri = Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI;
1017 } else {
1018 mBaseUri = Downloads.Impl.CONTENT_URI;
1019 }
1020 }
1021
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001022 /** {@hide} */
1023 public void setAccessFilename(boolean accessFilename) {
1024 mAccessFilename = accessFilename;
1025 }
1026
Steve Howardeca77fc2010-09-12 18:49:08 -07001027 /**
Steve Howarda2709362010-07-02 17:12:48 -07001028 * Enqueue a new download. The download will start automatically once the download manager is
1029 * ready to execute it and connectivity is available.
1030 *
1031 * @param request the parameters specifying this download
1032 * @return an ID for the download, unique across the system. This ID is used to make future
1033 * calls related to this download.
1034 */
1035 public long enqueue(Request request) {
Steve Howardb8e07a52010-07-21 14:53:21 -07001036 ContentValues values = request.toContentValues(mPackageName);
Vasu Norief7e33b2010-10-20 13:26:02 -07001037 Uri downloadUri = mResolver.insert(Downloads.Impl.CONTENT_URI, values);
Steve Howarda2709362010-07-02 17:12:48 -07001038 long id = Long.parseLong(downloadUri.getLastPathSegment());
1039 return id;
1040 }
1041
1042 /**
Vasu Nori216fa222010-10-12 23:08:13 -07001043 * Marks the specified download as 'to be deleted'. This is done when a completed download
1044 * is to be removed but the row was stored without enough info to delete the corresponding
1045 * metadata from Mediaprovider database. Actual cleanup of this row is done in DownloadService.
1046 *
1047 * @param ids the IDs of the downloads to be marked 'deleted'
1048 * @return the number of downloads actually updated
1049 * @hide
1050 */
1051 public int markRowDeleted(long... ids) {
1052 if (ids == null || ids.length == 0) {
1053 // called with nothing to remove!
1054 throw new IllegalArgumentException("input param 'ids' can't be null");
1055 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001056 return mResolver.delete(mBaseUri, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
Vasu Nori216fa222010-10-12 23:08:13 -07001057 }
1058
1059 /**
Steve Howard64c48b82010-10-07 17:53:52 -07001060 * Cancel downloads and remove them from the download manager. Each download will be stopped if
Vasu Nori17ee56c2011-02-28 08:35:39 -08001061 * it was running, and it will no longer be accessible through the download manager.
1062 * If there is a downloaded file, partial or complete, it is deleted.
Steve Howarda2709362010-07-02 17:12:48 -07001063 *
Steve Howard64c48b82010-10-07 17:53:52 -07001064 * @param ids the IDs of the downloads to remove
1065 * @return the number of downloads actually removed
Steve Howarda2709362010-07-02 17:12:48 -07001066 */
Steve Howard64c48b82010-10-07 17:53:52 -07001067 public int remove(long... ids) {
Vasu Norie16c43b2010-11-06 18:48:08 -07001068 return markRowDeleted(ids);
Steve Howarda2709362010-07-02 17:12:48 -07001069 }
1070
1071 /**
1072 * Query the download manager about downloads that have been requested.
1073 * @param query parameters specifying filters for this query
1074 * @return a Cursor over the result set of downloads, with columns consisting of all the
1075 * COLUMN_* constants.
1076 */
1077 public Cursor query(Query query) {
Steve Howardeca77fc2010-09-12 18:49:08 -07001078 Cursor underlyingCursor = query.runQuery(mResolver, UNDERLYING_COLUMNS, mBaseUri);
Steve Howardf054e192010-09-01 18:26:26 -07001079 if (underlyingCursor == null) {
1080 return null;
1081 }
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001082 return new CursorTranslator(underlyingCursor, mBaseUri, mAccessFilename);
Steve Howarda2709362010-07-02 17:12:48 -07001083 }
1084
1085 /**
1086 * Open a downloaded file for reading. The download must have completed.
1087 * @param id the ID of the download
1088 * @return a read-only {@link ParcelFileDescriptor}
1089 * @throws FileNotFoundException if the destination file does not already exist
1090 */
1091 public ParcelFileDescriptor openDownloadedFile(long id) throws FileNotFoundException {
1092 return mResolver.openFileDescriptor(getDownloadUri(id), "r");
1093 }
1094
1095 /**
John Spurlock92a262c2013-11-04 16:25:38 -05001096 * Returns the {@link Uri} of the given downloaded file id, if the file is
1097 * downloaded successfully. Otherwise, null is returned.
Vasu Nori5be894e2010-11-02 21:55:30 -07001098 *
1099 * @param id the id of the downloaded file.
Jeff Sharkeyb11683b2015-07-29 10:15:34 -07001100 * @return the {@link Uri} of the given downloaded file id, if download was
1101 * successful. null otherwise.
Vasu Nori5be894e2010-11-02 21:55:30 -07001102 */
1103 public Uri getUriForDownloadedFile(long id) {
1104 // to check if the file is in cache, get its destination from the database
1105 Query query = new Query().setFilterById(id);
1106 Cursor cursor = null;
1107 try {
1108 cursor = query(query);
1109 if (cursor == null) {
1110 return null;
1111 }
Leon Scrogginsd75e64a2010-12-13 15:48:40 -05001112 if (cursor.moveToFirst()) {
Vasu Nori6e2b2a62010-11-16 17:58:22 -08001113 int status = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_STATUS));
Vasu Nori5be894e2010-11-02 21:55:30 -07001114 if (DownloadManager.STATUS_SUCCESSFUL == status) {
Jeff Sharkeydf42d732016-09-16 16:57:34 -06001115 return ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, id);
Vasu Nori5be894e2010-11-02 21:55:30 -07001116 }
1117 }
1118 } finally {
1119 if (cursor != null) {
1120 cursor.close();
1121 }
1122 }
1123 // downloaded file not found or its status is not 'successfully completed'
1124 return null;
1125 }
1126
1127 /**
John Spurlock92a262c2013-11-04 16:25:38 -05001128 * Returns the media type of the given downloaded file id, if the file was
1129 * downloaded successfully. Otherwise, null is returned.
Vasu Nori6e2b2a62010-11-16 17:58:22 -08001130 *
1131 * @param id the id of the downloaded file.
John Spurlock92a262c2013-11-04 16:25:38 -05001132 * @return the media type of the given downloaded file id, if download was successful. null
Vasu Nori6e2b2a62010-11-16 17:58:22 -08001133 * otherwise.
1134 */
1135 public String getMimeTypeForDownloadedFile(long id) {
1136 Query query = new Query().setFilterById(id);
1137 Cursor cursor = null;
1138 try {
1139 cursor = query(query);
1140 if (cursor == null) {
1141 return null;
1142 }
1143 while (cursor.moveToFirst()) {
1144 return cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_MEDIA_TYPE));
1145 }
1146 } finally {
1147 if (cursor != null) {
1148 cursor.close();
1149 }
1150 }
1151 // downloaded file not found or its status is not 'successfully completed'
1152 return null;
1153 }
1154
1155 /**
Steve Howard64c48b82010-10-07 17:53:52 -07001156 * Restart the given downloads, which must have already completed (successfully or not). This
Steve Howard90fb15a2010-09-09 16:13:41 -07001157 * method will only work when called from within the download manager's process.
Steve Howard64c48b82010-10-07 17:53:52 -07001158 * @param ids the IDs of the downloads
Steve Howard90fb15a2010-09-09 16:13:41 -07001159 * @hide
1160 */
Steve Howard64c48b82010-10-07 17:53:52 -07001161 public void restartDownload(long... ids) {
1162 Cursor cursor = query(new Query().setFilterById(ids));
Steve Howard90fb15a2010-09-09 16:13:41 -07001163 try {
Steve Howard64c48b82010-10-07 17:53:52 -07001164 for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
1165 int status = cursor.getInt(cursor.getColumnIndex(COLUMN_STATUS));
1166 if (status != STATUS_SUCCESSFUL && status != STATUS_FAILED) {
1167 throw new IllegalArgumentException("Cannot restart incomplete download: "
1168 + cursor.getLong(cursor.getColumnIndex(COLUMN_ID)));
1169 }
Steve Howard90fb15a2010-09-09 16:13:41 -07001170 }
1171 } finally {
1172 cursor.close();
1173 }
1174
1175 ContentValues values = new ContentValues();
1176 values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, 0);
1177 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, -1);
1178 values.putNull(Downloads.Impl._DATA);
1179 values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING);
Jeff Sharkey54781202013-01-17 17:27:33 -08001180 values.put(Downloads.Impl.COLUMN_FAILED_CONNECTIONS, 0);
Steve Howard64c48b82010-10-07 17:53:52 -07001181 mResolver.update(mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
Steve Howard90fb15a2010-09-09 16:13:41 -07001182 }
1183
1184 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001185 * Force the given downloads to proceed even if their size is larger than
1186 * {@link #getMaxBytesOverMobile(Context)}.
1187 *
1188 * @hide
1189 */
1190 public void forceDownload(long... ids) {
1191 ContentValues values = new ContentValues();
1192 values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING);
1193 values.put(Downloads.Impl.COLUMN_CONTROL, Downloads.Impl.CONTROL_RUN);
1194 values.put(Downloads.Impl.COLUMN_BYPASS_RECOMMENDED_SIZE_LIMIT, 1);
1195 mResolver.update(mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
1196 }
1197
1198 /**
Vasu Nori0abbf802011-01-17 15:08:14 -08001199 * Returns maximum size, in bytes, of downloads that may go over a mobile connection; or null if
1200 * there's no limit
1201 *
1202 * @param context the {@link Context} to use for accessing the {@link ContentResolver}
1203 * @return maximum size, in bytes, of downloads that may go over a mobile connection; or null if
1204 * there's no limit
1205 */
1206 public static Long getMaxBytesOverMobile(Context context) {
1207 try {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001208 return Settings.Global.getLong(context.getContentResolver(),
1209 Settings.Global.DOWNLOAD_MAX_BYTES_OVER_MOBILE);
Vasu Nori0abbf802011-01-17 15:08:14 -08001210 } catch (SettingNotFoundException exc) {
1211 return null;
1212 }
1213 }
1214
1215 /**
Ben Lin726bf6a2016-04-27 11:38:05 -07001216 * Rename the given download if the download has completed
1217 *
1218 * @param context the {@link Context} to use in case need to update MediaProvider
1219 * @param id the downloaded id
1220 * @param displayName the new name to rename to
1221 * @return true if rename was successful, false otherwise
1222 * @hide
1223 */
1224 public boolean rename(Context context, long id, String displayName) {
1225 if (!FileUtils.isValidFatFilename(displayName)) {
1226 throw new SecurityException(displayName + " is not a valid filename");
1227 }
1228
1229 Query query = new Query().setFilterById(id);
1230 Cursor cursor = null;
1231 String oldDisplayName = null;
1232 String mimeType = null;
1233 try {
1234 cursor = query(query);
1235 if (cursor == null) {
1236 return false;
1237 }
1238 if (cursor.moveToFirst()) {
1239 int status = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_STATUS));
1240 if (DownloadManager.STATUS_SUCCESSFUL != status) {
1241 return false;
1242 }
1243 oldDisplayName = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_TITLE));
1244 mimeType = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_MEDIA_TYPE));
1245 }
1246 } finally {
1247 if (cursor != null) {
1248 cursor.close();
1249 }
1250 }
1251
1252 if (oldDisplayName == null || mimeType == null) {
1253 throw new IllegalStateException(
1254 "Document with id " + id + " does not exist");
1255 }
1256
1257 final File parent = Environment.getExternalStoragePublicDirectory(
1258 Environment.DIRECTORY_DOWNLOADS);
1259
1260 final File before = new File(parent, oldDisplayName);
1261 final File after = new File(parent, displayName);
1262
1263 if (after.exists()) {
1264 throw new IllegalStateException("Already exists " + after);
1265 }
1266 if (!before.renameTo(after)) {
1267 throw new IllegalStateException("Failed to rename to " + after);
1268 }
1269
1270 // Update MediaProvider if necessary
1271 if (mimeType.startsWith("image/")) {
1272 context.getContentResolver().delete(Images.Media.EXTERNAL_CONTENT_URI,
1273 Images.Media.DATA + "=?",
1274 new String[] {
1275 before.getAbsolutePath()
1276 });
1277
1278 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1279 intent.setData(Uri.fromFile(after));
1280 context.sendBroadcast(intent);
1281 }
1282
1283 ContentValues values = new ContentValues();
1284 values.put(Downloads.Impl.COLUMN_TITLE, displayName);
1285 values.put(Downloads.Impl._DATA, after.toString());
1286 values.putNull(Downloads.Impl.COLUMN_MEDIAPROVIDER_URI);
1287 long[] ids = {id};
1288
1289 return (mResolver.update(mBaseUri, values, getWhereClauseForIds(ids),
1290 getWhereArgsForIds(ids)) == 1);
1291 }
1292
1293 /**
Vasu Nori0abbf802011-01-17 15:08:14 -08001294 * Returns recommended maximum size, in bytes, of downloads that may go over a mobile
1295 * connection; or null if there's no recommended limit. The user will have the option to bypass
1296 * this limit.
1297 *
1298 * @param context the {@link Context} to use for accessing the {@link ContentResolver}
1299 * @return recommended maximum size, in bytes, of downloads that may go over a mobile
1300 * connection; or null if there's no recommended limit.
1301 */
1302 public static Long getRecommendedMaxBytesOverMobile(Context context) {
1303 try {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001304 return Settings.Global.getLong(context.getContentResolver(),
1305 Settings.Global.DOWNLOAD_RECOMMENDED_MAX_BYTES_OVER_MOBILE);
Vasu Nori0abbf802011-01-17 15:08:14 -08001306 } catch (SettingNotFoundException exc) {
1307 return null;
1308 }
1309 }
Vasu Noric0e50752011-01-20 17:57:54 -08001310
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001311 /** {@hide} */
1312 public static boolean isActiveNetworkExpensive(Context context) {
1313 // TODO: connect to NetworkPolicyManager
1314 return false;
1315 }
1316
1317 /** {@hide} */
1318 public static long getActiveNetworkWarningBytes(Context context) {
1319 // TODO: connect to NetworkPolicyManager
1320 return -1;
1321 }
1322
Vasu Noric0e50752011-01-20 17:57:54 -08001323 /**
1324 * Adds a file to the downloads database system, so it could appear in Downloads App
1325 * (and thus become eligible for management by the Downloads App).
1326 * <p>
1327 * It is helpful to make the file scannable by MediaScanner by setting the param
1328 * isMediaScannerScannable to true. It makes the file visible in media managing
1329 * applications such as Gallery App, which could be a useful purpose of using this API.
1330 *
1331 * @param title the title that would appear for this file in Downloads App.
1332 * @param description the description that would appear for this file in Downloads App.
1333 * @param isMediaScannerScannable true if the file is to be scanned by MediaScanner. Files
1334 * scanned by MediaScanner appear in the applications used to view media (for example,
1335 * Gallery app).
1336 * @param mimeType mimetype of the file.
1337 * @param path absolute pathname to the file. The file should be world-readable, so that it can
1338 * be managed by the Downloads App and any other app that is used to read it (for example,
1339 * Gallery app to display the file, if the file contents represent a video/image).
1340 * @param length length of the downloaded file
Vasu Norif9e85232011-02-10 14:59:54 -08001341 * @param showNotification true if a notification is to be sent, false otherwise
Vasu Noric0e50752011-01-20 17:57:54 -08001342 * @return an ID for the download entry added to the downloads app, unique across the system
1343 * This ID is used to make future calls related to this download.
1344 */
Vasu Nori37281302011-03-07 11:25:01 -08001345 public long addCompletedDownload(String title, String description,
Vasu Norif9e85232011-02-10 14:59:54 -08001346 boolean isMediaScannerScannable, String mimeType, String path, long length,
1347 boolean showNotification) {
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001348 return addCompletedDownload(title, description, isMediaScannerScannable, mimeType, path,
Edward Cunninghamabb2c5a2016-03-25 20:56:31 +00001349 length, showNotification, false, null, null);
1350 }
1351
1352 /**
1353 * Adds a file to the downloads database system, so it could appear in Downloads App
1354 * (and thus become eligible for management by the Downloads App).
1355 * <p>
1356 * It is helpful to make the file scannable by MediaScanner by setting the param
1357 * isMediaScannerScannable to true. It makes the file visible in media managing
1358 * applications such as Gallery App, which could be a useful purpose of using this API.
1359 *
1360 * @param title the title that would appear for this file in Downloads App.
1361 * @param description the description that would appear for this file in Downloads App.
1362 * @param isMediaScannerScannable true if the file is to be scanned by MediaScanner. Files
1363 * scanned by MediaScanner appear in the applications used to view media (for example,
1364 * Gallery app).
1365 * @param mimeType mimetype of the file.
1366 * @param path absolute pathname to the file. The file should be world-readable, so that it can
1367 * be managed by the Downloads App and any other app that is used to read it (for example,
1368 * Gallery app to display the file, if the file contents represent a video/image).
1369 * @param length length of the downloaded file
1370 * @param showNotification true if a notification is to be sent, false otherwise
1371 * @param uri the original HTTP URI of the download
1372 * @param referer the HTTP Referer for the download
1373 * @return an ID for the download entry added to the downloads app, unique across the system
1374 * This ID is used to make future calls related to this download.
1375 */
1376 public long addCompletedDownload(String title, String description,
1377 boolean isMediaScannerScannable, String mimeType, String path, long length,
1378 boolean showNotification, Uri uri, Uri referer) {
1379 return addCompletedDownload(title, description, isMediaScannerScannable, mimeType, path,
1380 length, showNotification, false, uri, referer);
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001381 }
1382
1383 /** {@hide} */
1384 public long addCompletedDownload(String title, String description,
1385 boolean isMediaScannerScannable, String mimeType, String path, long length,
1386 boolean showNotification, boolean allowWrite) {
Edward Cunninghamabb2c5a2016-03-25 20:56:31 +00001387 return addCompletedDownload(title, description, isMediaScannerScannable, mimeType, path,
1388 length, showNotification, allowWrite, null, null);
1389 }
1390
1391 /** {@hide} */
1392 public long addCompletedDownload(String title, String description,
1393 boolean isMediaScannerScannable, String mimeType, String path, long length,
1394 boolean showNotification, boolean allowWrite, Uri uri, Uri referer) {
Vasu Noric0e50752011-01-20 17:57:54 -08001395 // make sure the input args are non-null/non-zero
1396 validateArgumentIsNonEmpty("title", title);
1397 validateArgumentIsNonEmpty("description", description);
1398 validateArgumentIsNonEmpty("path", path);
1399 validateArgumentIsNonEmpty("mimeType", mimeType);
Jeff Sharkey33f95ed2012-05-02 17:07:54 -07001400 if (length < 0) {
Vasu Noric0e50752011-01-20 17:57:54 -08001401 throw new IllegalArgumentException(" invalid value for param: totalBytes");
1402 }
1403
1404 // if there is already an entry with the given path name in downloads.db, return its id
Edward Cunninghamabb2c5a2016-03-25 20:56:31 +00001405 Request request;
1406 if (uri != null) {
1407 request = new Request(uri);
1408 } else {
1409 request = new Request(NON_DOWNLOADMANAGER_DOWNLOAD);
1410 }
1411 request.setTitle(title)
Vasu Noric0e50752011-01-20 17:57:54 -08001412 .setDescription(description)
1413 .setMimeType(mimeType);
Edward Cunninghamabb2c5a2016-03-25 20:56:31 +00001414 if (referer != null) {
1415 request.addRequestHeader("Referer", referer.toString());
1416 }
Vasu Noric0e50752011-01-20 17:57:54 -08001417 ContentValues values = request.toContentValues(null);
1418 values.put(Downloads.Impl.COLUMN_DESTINATION,
1419 Downloads.Impl.DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD);
1420 values.put(Downloads.Impl._DATA, path);
1421 values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_SUCCESS);
1422 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, length);
1423 values.put(Downloads.Impl.COLUMN_MEDIA_SCANNED,
1424 (isMediaScannerScannable) ? Request.SCANNABLE_VALUE_YES :
1425 Request.SCANNABLE_VALUE_NO);
Vasu Norif9e85232011-02-10 14:59:54 -08001426 values.put(Downloads.Impl.COLUMN_VISIBILITY, (showNotification) ?
1427 Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION : Request.VISIBILITY_HIDDEN);
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001428 values.put(Downloads.Impl.COLUMN_ALLOW_WRITE, allowWrite ? 1 : 0);
Vasu Noric0e50752011-01-20 17:57:54 -08001429 Uri downloadUri = mResolver.insert(Downloads.Impl.CONTENT_URI, values);
1430 if (downloadUri == null) {
1431 return -1;
1432 }
1433 return Long.parseLong(downloadUri.getLastPathSegment());
1434 }
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001435
Vasu Noric0e50752011-01-20 17:57:54 -08001436 private static final String NON_DOWNLOADMANAGER_DOWNLOAD =
1437 "non-dwnldmngr-download-dont-retry2download";
1438
1439 private static void validateArgumentIsNonEmpty(String paramName, String val) {
1440 if (TextUtils.isEmpty(val)) {
1441 throw new IllegalArgumentException(paramName + " can't be null");
1442 }
1443 }
1444
Vasu Nori0abbf802011-01-17 15:08:14 -08001445 /**
Steve Howarda2709362010-07-02 17:12:48 -07001446 * Get the DownloadProvider URI for the download with the given ID.
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001447 *
1448 * @hide
Steve Howarda2709362010-07-02 17:12:48 -07001449 */
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001450 public Uri getDownloadUri(long id) {
Jeff Sharkey15471942016-09-16 12:04:05 -06001451 return ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, id);
Steve Howarda2709362010-07-02 17:12:48 -07001452 }
1453
1454 /**
Steve Howard64c48b82010-10-07 17:53:52 -07001455 * Get a parameterized SQL WHERE clause to select a bunch of IDs.
1456 */
1457 static String getWhereClauseForIds(long[] ids) {
1458 StringBuilder whereClause = new StringBuilder();
Vasu Norie7be6bd2010-10-10 14:58:08 -07001459 whereClause.append("(");
Steve Howard64c48b82010-10-07 17:53:52 -07001460 for (int i = 0; i < ids.length; i++) {
1461 if (i > 0) {
Vasu Norie7be6bd2010-10-10 14:58:08 -07001462 whereClause.append("OR ");
Steve Howard64c48b82010-10-07 17:53:52 -07001463 }
Vasu Norie7be6bd2010-10-10 14:58:08 -07001464 whereClause.append(Downloads.Impl._ID);
1465 whereClause.append(" = ? ");
Steve Howard64c48b82010-10-07 17:53:52 -07001466 }
1467 whereClause.append(")");
1468 return whereClause.toString();
1469 }
1470
1471 /**
1472 * Get the selection args for a clause returned by {@link #getWhereClauseForIds(long[])}.
1473 */
1474 static String[] getWhereArgsForIds(long[] ids) {
1475 String[] whereArgs = new String[ids.length];
Ben Lince763d82016-05-02 16:45:45 -07001476 return getWhereArgsForIds(ids, whereArgs);
Steve Howard64c48b82010-10-07 17:53:52 -07001477 }
1478
1479 /**
Ben Lince763d82016-05-02 16:45:45 -07001480 * Get selection args for a clause returned by {@link #getWhereClauseForIds(long[])}
1481 * and write it to the supplied args array.
1482 */
1483 static String[] getWhereArgsForIds(long[] ids, String[] args) {
1484 assert(args.length >= ids.length);
1485 for (int i = 0; i < ids.length; i++) {
1486 args[i] = Long.toString(ids[i]);
1487 }
1488 return args;
1489 }
1490
1491
1492 /**
Steve Howarda2709362010-07-02 17:12:48 -07001493 * This class wraps a cursor returned by DownloadProvider -- the "underlying cursor" -- and
1494 * presents a different set of columns, those defined in the DownloadManager.COLUMN_* constants.
1495 * Some columns correspond directly to underlying values while others are computed from
1496 * underlying data.
1497 */
1498 private static class CursorTranslator extends CursorWrapper {
Jeff Sharkey60cfad82016-01-05 17:30:57 -07001499 private final Uri mBaseUri;
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001500 private final boolean mAccessFilename;
Steve Howardeca77fc2010-09-12 18:49:08 -07001501
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001502 public CursorTranslator(Cursor cursor, Uri baseUri, boolean accessFilename) {
Steve Howarda2709362010-07-02 17:12:48 -07001503 super(cursor);
Steve Howardeca77fc2010-09-12 18:49:08 -07001504 mBaseUri = baseUri;
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001505 mAccessFilename = accessFilename;
Steve Howarda2709362010-07-02 17:12:48 -07001506 }
1507
1508 @Override
Steve Howarda2709362010-07-02 17:12:48 -07001509 public int getInt(int columnIndex) {
1510 return (int) getLong(columnIndex);
1511 }
1512
1513 @Override
1514 public long getLong(int columnIndex) {
Vasu Norie16c43b2010-11-06 18:48:08 -07001515 if (getColumnName(columnIndex).equals(COLUMN_REASON)) {
1516 return getReason(super.getInt(getColumnIndex(Downloads.Impl.COLUMN_STATUS)));
1517 } else if (getColumnName(columnIndex).equals(COLUMN_STATUS)) {
1518 return translateStatus(super.getInt(getColumnIndex(Downloads.Impl.COLUMN_STATUS)));
1519 } else {
1520 return super.getLong(columnIndex);
1521 }
Steve Howarda2709362010-07-02 17:12:48 -07001522 }
1523
1524 @Override
1525 public String getString(int columnIndex) {
Jeff Sharkey60cfad82016-01-05 17:30:57 -07001526 final String columnName = getColumnName(columnIndex);
1527 switch (columnName) {
1528 case COLUMN_LOCAL_URI:
1529 return getLocalUri();
1530 case COLUMN_LOCAL_FILENAME:
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001531 if (!mAccessFilename) {
Jeff Sharkey0c2ccd02016-03-22 10:05:47 -06001532 throw new SecurityException(
Jeff Sharkey60cfad82016-01-05 17:30:57 -07001533 "COLUMN_LOCAL_FILENAME is deprecated;"
1534 + " use ContentResolver.openFileDescriptor() instead");
1535 }
1536 default:
1537 return super.getString(columnIndex);
1538 }
Steve Howardeca77fc2010-09-12 18:49:08 -07001539 }
1540
1541 private String getLocalUri() {
Vasu Norie16c43b2010-11-06 18:48:08 -07001542 long destinationType = getLong(getColumnIndex(Downloads.Impl.COLUMN_DESTINATION));
1543 if (destinationType == Downloads.Impl.DESTINATION_FILE_URI ||
Vasu Noric0e50752011-01-20 17:57:54 -08001544 destinationType == Downloads.Impl.DESTINATION_EXTERNAL ||
1545 destinationType == Downloads.Impl.DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD) {
Jeff Sharkey281c1822016-03-30 19:46:42 -06001546 String localPath = super.getString(getColumnIndex(COLUMN_LOCAL_FILENAME));
Steve Howard99047d72010-09-29 17:41:37 -07001547 if (localPath == null) {
1548 return null;
1549 }
1550 return Uri.fromFile(new File(localPath)).toString();
Steve Howardbb0d23b2010-09-22 18:56:29 -07001551 }
1552
Steve Howardeca77fc2010-09-12 18:49:08 -07001553 // return content URI for cache download
Vasu Norie16c43b2010-11-06 18:48:08 -07001554 long downloadId = getLong(getColumnIndex(Downloads.Impl._ID));
Jeff Sharkey15471942016-09-16 12:04:05 -06001555 return ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, downloadId).toString();
Steve Howarda2709362010-07-02 17:12:48 -07001556 }
1557
Steve Howard3e8c1d32010-09-29 17:03:32 -07001558 private long getReason(int status) {
1559 switch (translateStatus(status)) {
1560 case STATUS_FAILED:
1561 return getErrorCode(status);
1562
1563 case STATUS_PAUSED:
1564 return getPausedReason(status);
1565
1566 default:
1567 return 0; // arbitrary value when status is not an error
Steve Howarda2709362010-07-02 17:12:48 -07001568 }
Steve Howard3e8c1d32010-09-29 17:03:32 -07001569 }
1570
1571 private long getPausedReason(int status) {
1572 switch (status) {
1573 case Downloads.Impl.STATUS_WAITING_TO_RETRY:
1574 return PAUSED_WAITING_TO_RETRY;
1575
1576 case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
1577 return PAUSED_WAITING_FOR_NETWORK;
1578
1579 case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
1580 return PAUSED_QUEUED_FOR_WIFI;
1581
1582 default:
1583 return PAUSED_UNKNOWN;
1584 }
1585 }
1586
1587 private long getErrorCode(int status) {
Steve Howard33bbd122010-08-02 17:51:29 -07001588 if ((400 <= status && status < Downloads.Impl.MIN_ARTIFICIAL_ERROR_STATUS)
1589 || (500 <= status && status < 600)) {
Steve Howarda2709362010-07-02 17:12:48 -07001590 // HTTP status code
1591 return status;
1592 }
1593
1594 switch (status) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001595 case Downloads.Impl.STATUS_FILE_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001596 return ERROR_FILE_ERROR;
1597
Vasu Norief7e33b2010-10-20 13:26:02 -07001598 case Downloads.Impl.STATUS_UNHANDLED_HTTP_CODE:
1599 case Downloads.Impl.STATUS_UNHANDLED_REDIRECT:
Steve Howarda2709362010-07-02 17:12:48 -07001600 return ERROR_UNHANDLED_HTTP_CODE;
1601
Vasu Norief7e33b2010-10-20 13:26:02 -07001602 case Downloads.Impl.STATUS_HTTP_DATA_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001603 return ERROR_HTTP_DATA_ERROR;
1604
Vasu Norief7e33b2010-10-20 13:26:02 -07001605 case Downloads.Impl.STATUS_TOO_MANY_REDIRECTS:
Steve Howarda2709362010-07-02 17:12:48 -07001606 return ERROR_TOO_MANY_REDIRECTS;
1607
Vasu Norief7e33b2010-10-20 13:26:02 -07001608 case Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001609 return ERROR_INSUFFICIENT_SPACE;
1610
Vasu Norief7e33b2010-10-20 13:26:02 -07001611 case Downloads.Impl.STATUS_DEVICE_NOT_FOUND_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001612 return ERROR_DEVICE_NOT_FOUND;
1613
Steve Howard33bbd122010-08-02 17:51:29 -07001614 case Downloads.Impl.STATUS_CANNOT_RESUME:
1615 return ERROR_CANNOT_RESUME;
1616
Steve Howarda9e87c92010-09-16 12:02:03 -07001617 case Downloads.Impl.STATUS_FILE_ALREADY_EXISTS_ERROR:
1618 return ERROR_FILE_ALREADY_EXISTS;
1619
Steve Howarda2709362010-07-02 17:12:48 -07001620 default:
1621 return ERROR_UNKNOWN;
1622 }
1623 }
1624
Steve Howard3e8c1d32010-09-29 17:03:32 -07001625 private int translateStatus(int status) {
Steve Howarda2709362010-07-02 17:12:48 -07001626 switch (status) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001627 case Downloads.Impl.STATUS_PENDING:
Steve Howarda2709362010-07-02 17:12:48 -07001628 return STATUS_PENDING;
1629
Vasu Norief7e33b2010-10-20 13:26:02 -07001630 case Downloads.Impl.STATUS_RUNNING:
Steve Howarda2709362010-07-02 17:12:48 -07001631 return STATUS_RUNNING;
1632
Steve Howard3e8c1d32010-09-29 17:03:32 -07001633 case Downloads.Impl.STATUS_PAUSED_BY_APP:
1634 case Downloads.Impl.STATUS_WAITING_TO_RETRY:
1635 case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
1636 case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
Steve Howarda2709362010-07-02 17:12:48 -07001637 return STATUS_PAUSED;
1638
Vasu Norief7e33b2010-10-20 13:26:02 -07001639 case Downloads.Impl.STATUS_SUCCESS:
Steve Howarda2709362010-07-02 17:12:48 -07001640 return STATUS_SUCCESSFUL;
1641
1642 default:
Vasu Norief7e33b2010-10-20 13:26:02 -07001643 assert Downloads.Impl.isStatusError(status);
Steve Howarda2709362010-07-02 17:12:48 -07001644 return STATUS_FAILED;
1645 }
1646 }
1647 }
1648}