blob: 1166cb57cca7941ae2ea13b73083bdd932b7ec89 [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;
Sudheer Shanka957954b2019-02-28 13:33:39 -080024import android.annotation.TestApi;
Mathew Inwood61e8ae62018-08-14 14:17:44 +010025import android.annotation.UnsupportedAppUsage;
Sudheer Shanka25f1c6e2019-04-22 17:03:47 -070026import android.content.ContentProviderClient;
Steve Howarda2709362010-07-02 17:12:48 -070027import android.content.ContentResolver;
Steve Howardeca77fc2010-09-12 18:49:08 -070028import android.content.ContentUris;
Steve Howarda2709362010-07-02 17:12:48 -070029import android.content.ContentValues;
Steve Howard4f564cd2010-09-22 15:57:25 -070030import android.content.Context;
Steve Howarda2709362010-07-02 17:12:48 -070031import android.database.Cursor;
32import android.database.CursorWrapper;
Sudheer Shankac4229172019-04-25 17:52:10 -070033import android.database.DatabaseUtils;
Steve Howardd58429f2010-09-27 16:32:39 -070034import android.net.ConnectivityManager;
Jeff Sharkey1a303952011-06-16 13:04:20 -070035import android.net.NetworkPolicyManager;
Steve Howardd58429f2010-09-27 16:32:39 -070036import android.net.Uri;
Jeff Sharkey60cfad82016-01-05 17:30:57 -070037import android.os.Build;
Sudheer Shanka25f1c6e2019-04-22 17:03:47 -070038import android.os.Bundle;
Steve Howard4f564cd2010-09-22 15:57:25 -070039import android.os.Environment;
Ben Lin726bf6a2016-04-27 11:38:05 -070040import android.os.FileUtils;
Steve Howarda2709362010-07-02 17:12:48 -070041import android.os.ParcelFileDescriptor;
Sudheer Shanka25f1c6e2019-04-22 17:03:47 -070042import android.os.RemoteException;
Steve Howarda2709362010-07-02 17:12:48 -070043import android.provider.Downloads;
Sudheer Shankac0ff9082019-05-23 10:47:30 -070044import android.provider.MediaStore;
Jeff Sharkey4233f032017-07-15 12:58:38 -060045import android.provider.Settings;
Vasu Nori0abbf802011-01-17 15:08:14 -080046import android.provider.Settings.SettingNotFoundException;
Vasu Noric0e50752011-01-20 17:57:54 -080047import android.text.TextUtils;
Steve Howard4f564cd2010-09-22 15:57:25 -070048import android.util.Pair;
Steve Howarda2709362010-07-02 17:12:48 -070049
Steve Howard4f564cd2010-09-22 15:57:25 -070050import java.io.File;
Steve Howarda2709362010-07-02 17:12:48 -070051import java.io.FileNotFoundException;
52import java.util.ArrayList;
Steve Howarda2709362010-07-02 17:12:48 -070053import java.util.List;
Steve Howarda2709362010-07-02 17:12:48 -070054
55/**
56 * The download manager is a system service that handles long-running HTTP downloads. Clients may
57 * request that a URI be downloaded to a particular destination file. The download manager will
58 * conduct the download in the background, taking care of HTTP interactions and retrying downloads
59 * after failures or across connectivity changes and system reboots.
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060060 * <p>
Steve Howard610c4352010-09-30 18:30:04 -070061 * Apps that request downloads through this API should register a broadcast receiver for
62 * {@link #ACTION_NOTIFICATION_CLICKED} to appropriately handle when the user clicks on a running
63 * download in a notification or from the downloads UI.
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060064 * <p>
Nicolas Falliere9530e3a2012-06-18 17:21:06 -070065 * Note that the application must have the {@link android.Manifest.permission#INTERNET}
66 * permission to use this class.
Steve Howarda2709362010-07-02 17:12:48 -070067 */
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060068@SystemService(Context.DOWNLOAD_SERVICE)
Steve Howarda2709362010-07-02 17:12:48 -070069public class DownloadManager {
Vasu Norie7be6bd2010-10-10 14:58:08 -070070
Steve Howarda2709362010-07-02 17:12:48 -070071 /**
72 * An identifier for a particular download, unique across the system. Clients use this ID to
73 * make subsequent calls related to the download.
74 */
Vasu Norief7e33b2010-10-20 13:26:02 -070075 public final static String COLUMN_ID = Downloads.Impl._ID;
Steve Howarda2709362010-07-02 17:12:48 -070076
77 /**
Steve Howard8651bd52010-08-03 12:35:32 -070078 * The client-supplied title for this download. This will be displayed in system notifications.
79 * 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_TITLE = Downloads.Impl.COLUMN_TITLE;
Steve Howarda2709362010-07-02 17:12:48 -070082
83 /**
84 * The client-supplied description of this download. This will be displayed in system
Steve Howard8651bd52010-08-03 12:35:32 -070085 * notifications. Defaults to the empty string.
Steve Howarda2709362010-07-02 17:12:48 -070086 */
Vasu Norief7e33b2010-10-20 13:26:02 -070087 public final static String COLUMN_DESCRIPTION = Downloads.Impl.COLUMN_DESCRIPTION;
Steve Howarda2709362010-07-02 17:12:48 -070088
89 /**
90 * URI to be downloaded.
91 */
Vasu Norief7e33b2010-10-20 13:26:02 -070092 public final static String COLUMN_URI = Downloads.Impl.COLUMN_URI;
Steve Howarda2709362010-07-02 17:12:48 -070093
94 /**
Steve Howard8651bd52010-08-03 12:35:32 -070095 * Internet Media Type of the downloaded file. If no value is provided upon creation, this will
96 * initially be null and will be filled in based on the server's response once the download has
97 * started.
Steve Howarda2709362010-07-02 17:12:48 -070098 *
99 * @see <a href="http://www.ietf.org/rfc/rfc1590.txt">RFC 1590, defining Media Types</a>
100 */
101 public final static String COLUMN_MEDIA_TYPE = "media_type";
102
103 /**
Steve Howard8651bd52010-08-03 12:35:32 -0700104 * Total size of the download in bytes. This will initially be -1 and will be filled in once
105 * the download starts.
Steve Howarda2709362010-07-02 17:12:48 -0700106 */
107 public final static String COLUMN_TOTAL_SIZE_BYTES = "total_size";
108
109 /**
110 * Uri where downloaded file will be stored. If a destination is supplied by client, that URI
Steve Howard8651bd52010-08-03 12:35:32 -0700111 * will be used here. Otherwise, the value will initially be null and will be filled in with a
112 * generated URI once the download has started.
Steve Howarda2709362010-07-02 17:12:48 -0700113 */
114 public final static String COLUMN_LOCAL_URI = "local_uri";
115
116 /**
Jeff Sharkey60cfad82016-01-05 17:30:57 -0700117 * Path to the downloaded file on disk.
118 * <p>
119 * Note that apps may not have filesystem permissions to directly access
120 * this path. Instead of trying to open this path directly, apps should use
121 * {@link ContentResolver#openFileDescriptor(Uri, String)} to gain access.
122 *
123 * @deprecated apps should transition to using
124 * {@link ContentResolver#openFileDescriptor(Uri, String)}
125 * instead.
Doug Zongkeree04af32010-10-08 13:42:16 -0700126 */
Jeff Sharkey60cfad82016-01-05 17:30:57 -0700127 @Deprecated
Doug Zongkeree04af32010-10-08 13:42:16 -0700128 public final static String COLUMN_LOCAL_FILENAME = "local_filename";
129
130 /**
Steve Howarda2709362010-07-02 17:12:48 -0700131 * Current status of the download, as one of the STATUS_* constants.
132 */
Vasu Norief7e33b2010-10-20 13:26:02 -0700133 public final static String COLUMN_STATUS = Downloads.Impl.COLUMN_STATUS;
Steve Howarda2709362010-07-02 17:12:48 -0700134
135 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700136 * Provides more detail on the status of the download. Its meaning depends on the value of
137 * {@link #COLUMN_STATUS}.
Steve Howarda2709362010-07-02 17:12:48 -0700138 *
Steve Howard3e8c1d32010-09-29 17:03:32 -0700139 * When {@link #COLUMN_STATUS} is {@link #STATUS_FAILED}, this indicates the type of error that
140 * occurred. If an HTTP error occurred, this will hold the HTTP status code as defined in RFC
141 * 2616. Otherwise, it will hold one of the ERROR_* constants.
142 *
143 * When {@link #COLUMN_STATUS} is {@link #STATUS_PAUSED}, this indicates why the download is
144 * paused. It will hold one of the PAUSED_* constants.
145 *
146 * If {@link #COLUMN_STATUS} is neither {@link #STATUS_FAILED} nor {@link #STATUS_PAUSED}, this
147 * column's value is undefined.
Steve Howarda2709362010-07-02 17:12:48 -0700148 *
149 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1.1">RFC 2616
150 * status codes</a>
151 */
Steve Howard3e8c1d32010-09-29 17:03:32 -0700152 public final static String COLUMN_REASON = "reason";
Steve Howarda2709362010-07-02 17:12:48 -0700153
154 /**
155 * Number of bytes download so far.
156 */
157 public final static String COLUMN_BYTES_DOWNLOADED_SO_FAR = "bytes_so_far";
158
159 /**
Steve Howardadcb6972010-07-12 17:09:25 -0700160 * Timestamp when the download was last modified, in {@link System#currentTimeMillis
Steve Howarda2709362010-07-02 17:12:48 -0700161 * System.currentTimeMillis()} (wall clock time in UTC).
162 */
Steve Howardadcb6972010-07-12 17:09:25 -0700163 public final static String COLUMN_LAST_MODIFIED_TIMESTAMP = "last_modified_timestamp";
Steve Howarda2709362010-07-02 17:12:48 -0700164
Vasu Nori216fa222010-10-12 23:08:13 -0700165 /**
166 * The URI to the corresponding entry in MediaProvider for this downloaded entry. It is
167 * used to delete the entries from MediaProvider database when it is deleted from the
168 * downloaded list.
169 */
Vasu Norief7e33b2010-10-20 13:26:02 -0700170 public static final String COLUMN_MEDIAPROVIDER_URI = Downloads.Impl.COLUMN_MEDIAPROVIDER_URI;
Steve Howarda2709362010-07-02 17:12:48 -0700171
Sudheer Shanka957954b2019-02-28 13:33:39 -0800172 /** @hide */
173 @TestApi
174 public static final String COLUMN_MEDIASTORE_URI = Downloads.Impl.COLUMN_MEDIASTORE_URI;
175
Steve Howarda2709362010-07-02 17:12:48 -0700176 /**
Jeff Sharkeyb180a652013-09-23 14:23:41 -0700177 * @hide
178 */
179 public final static String COLUMN_ALLOW_WRITE = Downloads.Impl.COLUMN_ALLOW_WRITE;
180
181 /**
Steve Howarda2709362010-07-02 17:12:48 -0700182 * Value of {@link #COLUMN_STATUS} when the download is waiting to start.
183 */
184 public final static int STATUS_PENDING = 1 << 0;
185
186 /**
187 * Value of {@link #COLUMN_STATUS} when the download is currently running.
188 */
189 public final static int STATUS_RUNNING = 1 << 1;
190
191 /**
192 * Value of {@link #COLUMN_STATUS} when the download is waiting to retry or resume.
193 */
194 public final static int STATUS_PAUSED = 1 << 2;
195
196 /**
197 * Value of {@link #COLUMN_STATUS} when the download has successfully completed.
198 */
199 public final static int STATUS_SUCCESSFUL = 1 << 3;
200
201 /**
202 * Value of {@link #COLUMN_STATUS} when the download has failed (and will not be retried).
203 */
204 public final static int STATUS_FAILED = 1 << 4;
205
Steve Howarda2709362010-07-02 17:12:48 -0700206 /**
207 * Value of COLUMN_ERROR_CODE when the download has completed with an error that doesn't fit
208 * under any other error code.
209 */
210 public final static int ERROR_UNKNOWN = 1000;
211
212 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700213 * Value of {@link #COLUMN_REASON} when a storage issue arises which doesn't fit under any
Steve Howarda2709362010-07-02 17:12:48 -0700214 * other error code. Use the more specific {@link #ERROR_INSUFFICIENT_SPACE} and
215 * {@link #ERROR_DEVICE_NOT_FOUND} when appropriate.
216 */
217 public final static int ERROR_FILE_ERROR = 1001;
218
219 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700220 * Value of {@link #COLUMN_REASON} when an HTTP code was received that download manager
Steve Howarda2709362010-07-02 17:12:48 -0700221 * can't handle.
222 */
223 public final static int ERROR_UNHANDLED_HTTP_CODE = 1002;
224
225 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700226 * Value of {@link #COLUMN_REASON} when an error receiving or processing data occurred at
Steve Howarda2709362010-07-02 17:12:48 -0700227 * the HTTP level.
228 */
229 public final static int ERROR_HTTP_DATA_ERROR = 1004;
230
231 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700232 * Value of {@link #COLUMN_REASON} when there were too many redirects.
Steve Howarda2709362010-07-02 17:12:48 -0700233 */
234 public final static int ERROR_TOO_MANY_REDIRECTS = 1005;
235
236 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700237 * Value of {@link #COLUMN_REASON} when there was insufficient storage space. Typically,
Steve Howarda2709362010-07-02 17:12:48 -0700238 * this is because the SD card is full.
239 */
240 public final static int ERROR_INSUFFICIENT_SPACE = 1006;
241
242 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700243 * Value of {@link #COLUMN_REASON} when no external storage device was found. Typically,
Steve Howarda2709362010-07-02 17:12:48 -0700244 * this is because the SD card is not mounted.
245 */
246 public final static int ERROR_DEVICE_NOT_FOUND = 1007;
247
Steve Howardb8e07a52010-07-21 14:53:21 -0700248 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700249 * Value of {@link #COLUMN_REASON} when some possibly transient error occurred but we can't
Steve Howard33bbd122010-08-02 17:51:29 -0700250 * resume the download.
251 */
252 public final static int ERROR_CANNOT_RESUME = 1008;
253
254 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700255 * Value of {@link #COLUMN_REASON} when the requested destination file already exists (the
Steve Howarda9e87c92010-09-16 12:02:03 -0700256 * download manager will not overwrite an existing file).
257 */
258 public final static int ERROR_FILE_ALREADY_EXISTS = 1009;
259
260 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700261 * Value of {@link #COLUMN_REASON} when the download has failed because of
262 * {@link NetworkPolicyManager} controls on the requesting application.
263 *
264 * @hide
265 */
266 public final static int ERROR_BLOCKED = 1010;
267
268 /**
Steve Howard3e8c1d32010-09-29 17:03:32 -0700269 * Value of {@link #COLUMN_REASON} when the download is paused because some network error
270 * occurred and the download manager is waiting before retrying the request.
271 */
272 public final static int PAUSED_WAITING_TO_RETRY = 1;
273
274 /**
275 * Value of {@link #COLUMN_REASON} when the download is waiting for network connectivity to
276 * proceed.
277 */
278 public final static int PAUSED_WAITING_FOR_NETWORK = 2;
279
280 /**
281 * Value of {@link #COLUMN_REASON} when the download exceeds a size limit for downloads over
282 * the mobile network and the download manager is waiting for a Wi-Fi connection to proceed.
283 */
284 public final static int PAUSED_QUEUED_FOR_WIFI = 3;
285
286 /**
287 * Value of {@link #COLUMN_REASON} when the download is paused for some other reason.
288 */
289 public final static int PAUSED_UNKNOWN = 4;
290
291 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700292 * Broadcast intent action sent by the download manager when a download completes.
293 */
Jeff Sharkey32cd2fb2013-10-02 10:11:22 -0700294 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Steve Howardb8e07a52010-07-21 14:53:21 -0700295 public final static String ACTION_DOWNLOAD_COMPLETE = "android.intent.action.DOWNLOAD_COMPLETE";
296
297 /**
Steve Howard610c4352010-09-30 18:30:04 -0700298 * Broadcast intent action sent by the download manager when the user clicks on a running
299 * download, either from a system notification or from the downloads UI.
Steve Howardb8e07a52010-07-21 14:53:21 -0700300 */
Jeff Sharkey32cd2fb2013-10-02 10:11:22 -0700301 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
Steve Howardb8e07a52010-07-21 14:53:21 -0700302 public final static String ACTION_NOTIFICATION_CLICKED =
303 "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED";
304
305 /**
Steve Howarde78fc182010-09-24 14:59:36 -0700306 * Intent action to launch an activity to display all downloads.
307 */
Jeff Sharkey32cd2fb2013-10-02 10:11:22 -0700308 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
Steve Howarde78fc182010-09-24 14:59:36 -0700309 public final static String ACTION_VIEW_DOWNLOADS = "android.intent.action.VIEW_DOWNLOADS";
310
311 /**
Vasu Norie5f92242011-01-24 16:12:20 -0800312 * Intent extra included with {@link #ACTION_VIEW_DOWNLOADS} to start DownloadApp in
313 * sort-by-size mode.
314 */
315 public final static String INTENT_EXTRAS_SORT_BY_SIZE =
316 "android.app.DownloadManager.extra_sortBySize";
317
318 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700319 * Intent extra included with {@link #ACTION_DOWNLOAD_COMPLETE} intents, indicating the ID (as a
320 * long) of the download that just completed.
321 */
322 public static final String EXTRA_DOWNLOAD_ID = "extra_download_id";
Steve Howarda2709362010-07-02 17:12:48 -0700323
Vasu Nori71b8c232010-10-27 15:22:19 -0700324 /**
325 * When clicks on multiple notifications are received, the following
326 * provides an array of download ids corresponding to the download notification that was
327 * clicked. It can be retrieved by the receiver of this
328 * Intent using {@link android.content.Intent#getLongArrayExtra(String)}.
329 */
330 public static final String EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS = "extra_click_download_ids";
331
Jeff Sharkey8d5d0652017-04-04 14:38:39 -0600332 /** {@hide} */
333 @SystemApi
334 public static final String ACTION_DOWNLOAD_COMPLETED =
335 "android.intent.action.DOWNLOAD_COMPLETED";
336
Vasu Norie16c43b2010-11-06 18:48:08 -0700337 /**
338 * columns to request from DownloadProvider.
339 * @hide
340 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100341 @UnsupportedAppUsage
Vasu Norie16c43b2010-11-06 18:48:08 -0700342 public static final String[] UNDERLYING_COLUMNS = new String[] {
Steve Howarda2709362010-07-02 17:12:48 -0700343 Downloads.Impl._ID,
Vasu Norie69924f2010-11-15 13:10:11 -0800344 Downloads.Impl._DATA + " AS " + COLUMN_LOCAL_FILENAME,
Vasu Nori216fa222010-10-12 23:08:13 -0700345 Downloads.Impl.COLUMN_MEDIAPROVIDER_URI,
Vasu Nori5be894e2010-11-02 21:55:30 -0700346 Downloads.Impl.COLUMN_DESTINATION,
Vasu Norief7e33b2010-10-20 13:26:02 -0700347 Downloads.Impl.COLUMN_TITLE,
348 Downloads.Impl.COLUMN_DESCRIPTION,
349 Downloads.Impl.COLUMN_URI,
Vasu Norief7e33b2010-10-20 13:26:02 -0700350 Downloads.Impl.COLUMN_STATUS,
Steve Howarda9e87c92010-09-16 12:02:03 -0700351 Downloads.Impl.COLUMN_FILE_NAME_HINT,
Vasu Norie16c43b2010-11-06 18:48:08 -0700352 Downloads.Impl.COLUMN_MIME_TYPE + " AS " + COLUMN_MEDIA_TYPE,
353 Downloads.Impl.COLUMN_TOTAL_BYTES + " AS " + COLUMN_TOTAL_SIZE_BYTES,
354 Downloads.Impl.COLUMN_LAST_MODIFICATION + " AS " + COLUMN_LAST_MODIFIED_TIMESTAMP,
355 Downloads.Impl.COLUMN_CURRENT_BYTES + " AS " + COLUMN_BYTES_DOWNLOADED_SO_FAR,
Jeff Sharkeyb180a652013-09-23 14:23:41 -0700356 Downloads.Impl.COLUMN_ALLOW_WRITE,
Vasu Norie16c43b2010-11-06 18:48:08 -0700357 /* add the following 'computed' columns to the cursor.
358 * they are not 'returned' by the database, but their inclusion
359 * eliminates need to have lot of methods in CursorTranslator
360 */
361 "'placeholder' AS " + COLUMN_LOCAL_URI,
362 "'placeholder' AS " + COLUMN_REASON
Steve Howarda2709362010-07-02 17:12:48 -0700363 };
364
Steve Howarda2709362010-07-02 17:12:48 -0700365 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700366 * This class contains all the information necessary to request a new download. The URI is the
Steve Howarda2709362010-07-02 17:12:48 -0700367 * only required parameter.
Steve Howard4f564cd2010-09-22 15:57:25 -0700368 *
369 * Note that the default download destination is a shared volume where the system might delete
370 * your file if it needs to reclaim space for system use. If this is a problem, use a location
371 * on external storage (see {@link #setDestinationUri(Uri)}.
Steve Howarda2709362010-07-02 17:12:48 -0700372 */
373 public static class Request {
374 /**
Steve Howardb8e07a52010-07-21 14:53:21 -0700375 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
376 * {@link ConnectivityManager#TYPE_MOBILE}.
377 */
378 public static final int NETWORK_MOBILE = 1 << 0;
Steve Howarda2709362010-07-02 17:12:48 -0700379
Steve Howardb8e07a52010-07-21 14:53:21 -0700380 /**
381 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
382 * {@link ConnectivityManager#TYPE_WIFI}.
383 */
384 public static final int NETWORK_WIFI = 1 << 1;
385
HÃ¥kan3 Johansson011238b2012-02-08 21:13:35 +0100386 /**
387 * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
388 * {@link ConnectivityManager#TYPE_BLUETOOTH}.
389 * @hide
390 */
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600391 @Deprecated
HÃ¥kan3 Johansson011238b2012-02-08 21:13:35 +0100392 public static final int NETWORK_BLUETOOTH = 1 << 2;
393
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100394 @UnsupportedAppUsage
Steve Howardb8e07a52010-07-21 14:53:21 -0700395 private Uri mUri;
396 private Uri mDestinationUri;
Steve Howard4f564cd2010-09-22 15:57:25 -0700397 private List<Pair<String, String>> mRequestHeaders = new ArrayList<Pair<String, String>>();
398 private CharSequence mTitle;
399 private CharSequence mDescription;
Steve Howard4f564cd2010-09-22 15:57:25 -0700400 private String mMimeType;
Steve Howardb8e07a52010-07-21 14:53:21 -0700401 private int mAllowedNetworkTypes = ~0; // default to all network types allowed
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700402 private boolean mRoamingAllowed = true;
403 private boolean mMeteredAllowed = true;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600404 private int mFlags = 0;
Steve Howard90fb15a2010-09-09 16:13:41 -0700405 private boolean mIsVisibleInDownloadsUi = true;
Vasu Nori5be894e2010-11-02 21:55:30 -0700406 private boolean mScannable = false;
Vasu Nori1cde3fb2010-11-05 11:02:52 -0700407 /** if a file is designated as a MediaScanner scannable file, the following value is
408 * stored in the database column {@link Downloads.Impl#COLUMN_MEDIA_SCANNED}.
409 */
Sudheer Shanka684c02a2019-01-29 17:41:15 -0800410 private static final int SCANNABLE_VALUE_YES = Downloads.Impl.MEDIA_NOT_SCANNED;
Vasu Nori1cde3fb2010-11-05 11:02:52 -0700411 // value of 1 is stored in the above column by DownloadProvider after it is scanned by
412 // MediaScanner
413 /** if a file is designated as a file that should not be scanned by MediaScanner,
414 * the following value is stored in the database column
415 * {@link Downloads.Impl#COLUMN_MEDIA_SCANNED}.
416 */
Sudheer Shanka684c02a2019-01-29 17:41:15 -0800417 private static final int SCANNABLE_VALUE_NO = Downloads.Impl.MEDIA_NOT_SCANNABLE;
Steve Howarda2709362010-07-02 17:12:48 -0700418
419 /**
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700420 * This download is visible but only shows in the notifications
421 * while it's in progress.
422 */
423 public static final int VISIBILITY_VISIBLE = 0;
424
425 /**
426 * This download is visible and shows in the notifications while
427 * in progress and after completion.
428 */
429 public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED = 1;
430
431 /**
432 * This download doesn't show in the UI or in the notifications.
433 */
434 public static final int VISIBILITY_HIDDEN = 2;
435
Vasu Norif9e85232011-02-10 14:59:54 -0800436 /**
437 * This download shows in the notifications after completion ONLY.
438 * It is usuable only with
Vasu Nori37281302011-03-07 11:25:01 -0800439 * {@link DownloadManager#addCompletedDownload(String, String,
440 * boolean, String, String, long, boolean)}.
Vasu Norif9e85232011-02-10 14:59:54 -0800441 */
442 public static final int VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION = 3;
443
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700444 /** can take any of the following values: {@link #VISIBILITY_HIDDEN}
Vasu Norif9e85232011-02-10 14:59:54 -0800445 * {@link #VISIBILITY_VISIBLE_NOTIFY_COMPLETED}, {@link #VISIBILITY_VISIBLE},
446 * {@link #VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION}
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700447 */
448 private int mNotificationVisibility = VISIBILITY_VISIBLE;
449
450 /**
Alex Klyubin66629bc2015-06-11 14:34:44 -0700451 * @param uri the HTTP or HTTPS URI to download.
Steve Howarda2709362010-07-02 17:12:48 -0700452 */
453 public Request(Uri uri) {
454 if (uri == null) {
455 throw new NullPointerException();
456 }
457 String scheme = uri.getScheme();
Paul Westbrook86a60192010-09-15 12:55:49 -0700458 if (scheme == null || (!scheme.equals("http") && !scheme.equals("https"))) {
459 throw new IllegalArgumentException("Can only download HTTP/HTTPS URIs: " + uri);
Steve Howarda2709362010-07-02 17:12:48 -0700460 }
461 mUri = uri;
462 }
463
Vasu Noric0e50752011-01-20 17:57:54 -0800464 Request(String uriString) {
465 mUri = Uri.parse(uriString);
466 }
467
Steve Howarda2709362010-07-02 17:12:48 -0700468 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700469 * Set the local destination for the downloaded file. Must be a file URI to a path on
Steve Howarda2709362010-07-02 17:12:48 -0700470 * external storage, and the calling application must have the WRITE_EXTERNAL_STORAGE
471 * permission.
Vasu Nori5be894e2010-11-02 21:55:30 -0700472 * <p>
473 * The downloaded file is not scanned by MediaScanner.
474 * But it can be made scannable by calling {@link #allowScanningByMediaScanner()}.
475 * <p>
Steve Howard4f564cd2010-09-22 15:57:25 -0700476 * By default, downloads are saved to a generated filename in the shared download cache and
477 * may be deleted by the system at any time to reclaim space.
Steve Howarda2709362010-07-02 17:12:48 -0700478 *
Sudheer Shanka25f1c6e2019-04-22 17:03:47 -0700479 * <p> For applications targeting {@link android.os.Build.VERSION_CODES#Q} or above,
480 * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE WRITE EXTERNAL_STORAGE}
481 * permission is not needed and the {@code uri} must refer to a path within the
482 * directories owned by the application (e.g. {@link Context#getExternalFilesDir(String)})
483 * or a path within the top-level Downloads directory (as returned by
484 * {@link Environment#getExternalStoragePublicDirectory(String)} with
485 * {@link Environment#DIRECTORY_DOWNLOADS}).
486 *
487 * @param uri a file {@link Uri} indicating the destination for the downloaded file.
Steve Howarda2709362010-07-02 17:12:48 -0700488 * @return this object
489 */
490 public Request setDestinationUri(Uri uri) {
491 mDestinationUri = uri;
492 return this;
493 }
494
495 /**
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700496 * Set the local destination for the downloaded file to a path within
497 * the application's external files directory (as returned by
498 * {@link Context#getExternalFilesDir(String)}.
Vasu Nori5be894e2010-11-02 21:55:30 -0700499 * <p>
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700500 * The downloaded file is not scanned by MediaScanner. But it can be
501 * made scannable by calling {@link #allowScanningByMediaScanner()}.
Steve Howard4f564cd2010-09-22 15:57:25 -0700502 *
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700503 * @param context the {@link Context} to use in determining the external
504 * files directory
505 * @param dirType the directory type to pass to
506 * {@link Context#getExternalFilesDir(String)}
507 * @param subPath the path within the external directory, including the
508 * destination filename
Steve Howard4f564cd2010-09-22 15:57:25 -0700509 * @return this object
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700510 * @throws IllegalStateException If the external storage directory
511 * cannot be found or created.
Steve Howard4f564cd2010-09-22 15:57:25 -0700512 */
513 public Request setDestinationInExternalFilesDir(Context context, String dirType,
514 String subPath) {
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700515 final File file = context.getExternalFilesDir(dirType);
516 if (file == null) {
517 throw new IllegalStateException("Failed to get external storage files directory");
518 } else if (file.exists()) {
519 if (!file.isDirectory()) {
520 throw new IllegalStateException(file.getAbsolutePath() +
521 " already exists and is not a directory");
522 }
523 } else {
524 if (!file.mkdirs()) {
525 throw new IllegalStateException("Unable to create directory: "+
526 file.getAbsolutePath());
527 }
528 }
529 setDestinationFromBase(file, subPath);
Steve Howard4f564cd2010-09-22 15:57:25 -0700530 return this;
531 }
532
533 /**
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700534 * Set the local destination for the downloaded file to a path within
535 * the public external storage directory (as returned by
536 * {@link Environment#getExternalStoragePublicDirectory(String)}).
537 * <p>
538 * The downloaded file is not scanned by MediaScanner. But it can be
539 * made scannable by calling {@link #allowScanningByMediaScanner()}.
Steve Howard4f564cd2010-09-22 15:57:25 -0700540 *
Sudheer Shanka25f1c6e2019-04-22 17:03:47 -0700541 * <p> For applications targeting {@link android.os.Build.VERSION_CODES#Q} or above,
542 * {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE WRITE_EXTERNAL_STORAGE}
Sudheer Shankae707ddc2019-05-08 18:59:45 -0700543 * permission is not needed and the {@code dirType} must be one of the known public
544 * directories like {@link Environment#DIRECTORY_DOWNLOADS},
545 * {@link Environment#DIRECTORY_PICTURES}, {@link Environment#DIRECTORY_MOVIES}, etc.
Sudheer Shanka25f1c6e2019-04-22 17:03:47 -0700546 *
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700547 * @param dirType the directory type to pass to {@link Environment#getExternalStoragePublicDirectory(String)}
548 * @param subPath the path within the external directory, including the
549 * destination filename
Steve Howard4f564cd2010-09-22 15:57:25 -0700550 * @return this object
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700551 * @throws IllegalStateException If the external storage directory
552 * cannot be found or created.
Steve Howard4f564cd2010-09-22 15:57:25 -0700553 */
554 public Request setDestinationInExternalPublicDir(String dirType, String subPath) {
Vasu Nori6916b032010-12-19 20:31:00 -0800555 File file = Environment.getExternalStoragePublicDirectory(dirType);
Jeff Sharkey45d01ea2013-03-25 17:30:16 -0700556 if (file == null) {
557 throw new IllegalStateException("Failed to get external storage public directory");
Sudheer Shanka25f1c6e2019-04-22 17:03:47 -0700558 }
559
560 final Context context = AppGlobals.getInitialApplication();
561 if (context.getApplicationInfo().targetSdkVersion
Sudheer Shankaebcf0542019-04-24 18:30:32 -0700562 >= Build.VERSION_CODES.Q || !Environment.isExternalStorageLegacy()) {
Sudheer Shanka25f1c6e2019-04-22 17:03:47 -0700563 try (ContentProviderClient client = context.getContentResolver()
564 .acquireContentProviderClient(Downloads.Impl.AUTHORITY)) {
565 final Bundle extras = new Bundle();
566 extras.putString(Downloads.DIR_TYPE, dirType);
567 client.call(Downloads.CALL_CREATE_EXTERNAL_PUBLIC_DIR, null, extras);
568 } catch (RemoteException e) {
569 throw new IllegalStateException("Unable to create directory: "
570 + file.getAbsolutePath());
Vasu Nori6916b032010-12-19 20:31:00 -0800571 }
572 } else {
Sudheer Shanka25f1c6e2019-04-22 17:03:47 -0700573 if (file.exists()) {
574 if (!file.isDirectory()) {
575 throw new IllegalStateException(file.getAbsolutePath()
576 + " already exists and is not a directory");
577 }
578 } else if (!file.mkdirs()) {
579 throw new IllegalStateException("Unable to create directory: "
580 + file.getAbsolutePath());
Vasu Nori6916b032010-12-19 20:31:00 -0800581 }
582 }
583 setDestinationFromBase(file, subPath);
Steve Howard4f564cd2010-09-22 15:57:25 -0700584 return this;
585 }
586
587 private void setDestinationFromBase(File base, String subPath) {
588 if (subPath == null) {
589 throw new NullPointerException("subPath cannot be null");
590 }
591 mDestinationUri = Uri.withAppendedPath(Uri.fromFile(base), subPath);
592 }
593
594 /**
Vasu Nori5be894e2010-11-02 21:55:30 -0700595 * If the file to be downloaded is to be scanned by MediaScanner, this method
596 * should be called before {@link DownloadManager#enqueue(Request)} is called.
Sudheer Shanka5b2e6952019-04-28 16:00:53 +0000597 *
598 * @deprecated Starting in Q, this value is ignored. Files downloaded to
Sudheer Shankae707ddc2019-05-08 18:59:45 -0700599 * directories owned by applications (e.g. {@link Context#getExternalFilesDir(String)})
600 * will not be scanned by MediaScanner and the rest will be scanned.
Vasu Nori5be894e2010-11-02 21:55:30 -0700601 */
Sudheer Shanka5b2e6952019-04-28 16:00:53 +0000602 @Deprecated
Vasu Nori5be894e2010-11-02 21:55:30 -0700603 public void allowScanningByMediaScanner() {
604 mScannable = true;
605 }
606
607 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700608 * Add an HTTP header to be included with the download request. The header will be added to
609 * the end of the list.
Steve Howarda2709362010-07-02 17:12:48 -0700610 * @param header HTTP header name
611 * @param value header value
612 * @return this object
Steve Howard4f564cd2010-09-22 15:57:25 -0700613 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2">HTTP/1.1
614 * Message Headers</a>
Steve Howarda2709362010-07-02 17:12:48 -0700615 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700616 public Request addRequestHeader(String header, String value) {
617 if (header == null) {
618 throw new NullPointerException("header cannot be null");
619 }
620 if (header.contains(":")) {
621 throw new IllegalArgumentException("header may not contain ':'");
622 }
623 if (value == null) {
624 value = "";
625 }
626 mRequestHeaders.add(Pair.create(header, value));
Steve Howarda2709362010-07-02 17:12:48 -0700627 return this;
628 }
629
630 /**
Steve Howard610c4352010-09-30 18:30:04 -0700631 * Set the title of this download, to be displayed in notifications (if enabled). If no
632 * title is given, a default one will be assigned based on the download filename, once the
633 * download starts.
Steve Howarda2709362010-07-02 17:12:48 -0700634 * @return this object
635 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700636 public Request setTitle(CharSequence title) {
Steve Howarda2709362010-07-02 17:12:48 -0700637 mTitle = title;
638 return this;
639 }
640
641 /**
642 * Set a description of this download, to be displayed in notifications (if enabled)
643 * @return this object
644 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700645 public Request setDescription(CharSequence description) {
Steve Howarda2709362010-07-02 17:12:48 -0700646 mDescription = description;
647 return this;
648 }
649
650 /**
Steve Howard4f564cd2010-09-22 15:57:25 -0700651 * Set the MIME content type of this download. This will override the content type declared
Steve Howarda2709362010-07-02 17:12:48 -0700652 * in the server's response.
Steve Howard4f564cd2010-09-22 15:57:25 -0700653 * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7">HTTP/1.1
654 * Media Types</a>
Steve Howarda2709362010-07-02 17:12:48 -0700655 * @return this object
656 */
Steve Howard4f564cd2010-09-22 15:57:25 -0700657 public Request setMimeType(String mimeType) {
658 mMimeType = mimeType;
Steve Howarda2709362010-07-02 17:12:48 -0700659 return this;
660 }
661
662 /**
Steve Howard8e15afe2010-07-28 17:12:40 -0700663 * Control whether a system notification is posted by the download manager while this
664 * download is running. If enabled, the download manager posts notifications about downloads
665 * through the system {@link android.app.NotificationManager}. By default, a notification is
666 * shown.
Steve Howarda2709362010-07-02 17:12:48 -0700667 *
Steve Howard8e15afe2010-07-28 17:12:40 -0700668 * If set to false, this requires the permission
669 * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
670 *
671 * @param show whether the download manager should show a notification for this download.
Steve Howarda2709362010-07-02 17:12:48 -0700672 * @return this object
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700673 * @deprecated use {@link #setNotificationVisibility(int)}
Steve Howarda2709362010-07-02 17:12:48 -0700674 */
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700675 @Deprecated
Steve Howard8e15afe2010-07-28 17:12:40 -0700676 public Request setShowRunningNotification(boolean show) {
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700677 return (show) ? setNotificationVisibility(VISIBILITY_VISIBLE) :
678 setNotificationVisibility(VISIBILITY_HIDDEN);
679 }
680
681 /**
682 * Control whether a system notification is posted by the download manager while this
683 * download is running or when it is completed.
684 * If enabled, the download manager posts notifications about downloads
685 * through the system {@link android.app.NotificationManager}.
686 * By default, a notification is shown only when the download is in progress.
687 *<p>
688 * It can take the following values: {@link #VISIBILITY_HIDDEN},
689 * {@link #VISIBILITY_VISIBLE},
690 * {@link #VISIBILITY_VISIBLE_NOTIFY_COMPLETED}.
691 *<p>
692 * If set to {@link #VISIBILITY_HIDDEN}, this requires the permission
693 * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
694 *
695 * @param visibility the visibility setting value
696 * @return this object
697 */
698 public Request setNotificationVisibility(int visibility) {
699 mNotificationVisibility = visibility;
Steve Howarda2709362010-07-02 17:12:48 -0700700 return this;
701 }
702
Steve Howardb8e07a52010-07-21 14:53:21 -0700703 /**
Jeff Sharkey792e0912012-04-16 11:52:18 -0700704 * Restrict the types of networks over which this download may proceed.
705 * By default, all network types are allowed. Consider using
706 * {@link #setAllowedOverMetered(boolean)} instead, since it's more
707 * flexible.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600708 * <p>
709 * As of {@link android.os.Build.VERSION_CODES#N}, setting only the
710 * {@link #NETWORK_WIFI} flag here is equivalent to calling
711 * {@link #setAllowedOverMetered(boolean)} with {@code false}.
Jeff Sharkey792e0912012-04-16 11:52:18 -0700712 *
Steve Howardb8e07a52010-07-21 14:53:21 -0700713 * @param flags any combination of the NETWORK_* bit flags.
714 * @return this object
715 */
Steve Howarda2709362010-07-02 17:12:48 -0700716 public Request setAllowedNetworkTypes(int flags) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700717 mAllowedNetworkTypes = flags;
718 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700719 }
720
Steve Howardb8e07a52010-07-21 14:53:21 -0700721 /**
722 * Set whether this download may proceed over a roaming connection. By default, roaming is
723 * allowed.
724 * @param allowed whether to allow a roaming connection to be used
725 * @return this object
726 */
Steve Howarda2709362010-07-02 17:12:48 -0700727 public Request setAllowedOverRoaming(boolean allowed) {
Steve Howardb8e07a52010-07-21 14:53:21 -0700728 mRoamingAllowed = allowed;
729 return this;
Steve Howarda2709362010-07-02 17:12:48 -0700730 }
731
732 /**
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700733 * Set whether this download may proceed over a metered network
734 * connection. By default, metered networks are allowed.
735 *
736 * @see ConnectivityManager#isActiveNetworkMetered()
737 */
738 public Request setAllowedOverMetered(boolean allow) {
739 mMeteredAllowed = allow;
740 return this;
741 }
742
743 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600744 * Specify that to run this download, the device needs to be plugged in.
745 * This defaults to false.
746 *
747 * @param requiresCharging Whether or not the device is plugged in.
748 * @see android.app.job.JobInfo.Builder#setRequiresCharging(boolean)
749 */
750 public Request setRequiresCharging(boolean requiresCharging) {
751 if (requiresCharging) {
752 mFlags |= Downloads.Impl.FLAG_REQUIRES_CHARGING;
753 } else {
754 mFlags &= ~Downloads.Impl.FLAG_REQUIRES_CHARGING;
755 }
756 return this;
757 }
758
759 /**
760 * Specify that to run, the download needs the device to be in idle
761 * mode. This defaults to false.
762 * <p>
763 * Idle mode is a loose definition provided by the system, which means
764 * that the device is not in use, and has not been in use for some time.
765 *
766 * @param requiresDeviceIdle Whether or not the device need be within an
767 * idle maintenance window.
768 * @see android.app.job.JobInfo.Builder#setRequiresDeviceIdle(boolean)
769 */
770 public Request setRequiresDeviceIdle(boolean requiresDeviceIdle) {
771 if (requiresDeviceIdle) {
772 mFlags |= Downloads.Impl.FLAG_REQUIRES_DEVICE_IDLE;
773 } else {
774 mFlags &= ~Downloads.Impl.FLAG_REQUIRES_DEVICE_IDLE;
775 }
776 return this;
777 }
778
779 /**
Steve Howard90fb15a2010-09-09 16:13:41 -0700780 * Set whether this download should be displayed in the system's Downloads UI. True by
781 * default.
782 * @param isVisible whether to display this download in the Downloads UI
783 * @return this object
Sudheer Shanka5b2e6952019-04-28 16:00:53 +0000784 *
Sudheer Shankae707ddc2019-05-08 18:59:45 -0700785 * @deprecated Starting in Q, this value is ignored. Only files downloaded to
Sudheer Shanka5b2e6952019-04-28 16:00:53 +0000786 * public Downloads directory (as returned by
787 * {@link Environment#getExternalStoragePublicDirectory(String)} with
788 * {@link Environment#DIRECTORY_DOWNLOADS}) will be visible in system's Downloads UI
Sudheer Shankae707ddc2019-05-08 18:59:45 -0700789 * and the rest will not be visible.
Sudheer Shanka5b2e6952019-04-28 16:00:53 +0000790 * (e.g. {@link Context#getExternalFilesDir(String)}) will not be visible.
Steve Howard90fb15a2010-09-09 16:13:41 -0700791 */
Sudheer Shanka5b2e6952019-04-28 16:00:53 +0000792 @Deprecated
Steve Howard90fb15a2010-09-09 16:13:41 -0700793 public Request setVisibleInDownloadsUi(boolean isVisible) {
794 mIsVisibleInDownloadsUi = isVisible;
795 return this;
796 }
797
798 /**
Steve Howarda2709362010-07-02 17:12:48 -0700799 * @return ContentValues to be passed to DownloadProvider.insert()
800 */
Steve Howardb8e07a52010-07-21 14:53:21 -0700801 ContentValues toContentValues(String packageName) {
Steve Howarda2709362010-07-02 17:12:48 -0700802 ContentValues values = new ContentValues();
803 assert mUri != null;
Vasu Norief7e33b2010-10-20 13:26:02 -0700804 values.put(Downloads.Impl.COLUMN_URI, mUri.toString());
Steve Howardb8e07a52010-07-21 14:53:21 -0700805 values.put(Downloads.Impl.COLUMN_IS_PUBLIC_API, true);
Vasu Norief7e33b2010-10-20 13:26:02 -0700806 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE, packageName);
Steve Howarda2709362010-07-02 17:12:48 -0700807
808 if (mDestinationUri != null) {
Jeff Sharkey4233f032017-07-15 12:58:38 -0600809 values.put(Downloads.Impl.COLUMN_DESTINATION,
810 Downloads.Impl.DESTINATION_FILE_URI);
811 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT,
812 mDestinationUri.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700813 } else {
Vasu Norief7e33b2010-10-20 13:26:02 -0700814 values.put(Downloads.Impl.COLUMN_DESTINATION,
Jeff Sharkey4233f032017-07-15 12:58:38 -0600815 Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE);
Steve Howarda2709362010-07-02 17:12:48 -0700816 }
Vasu Nori5be894e2010-11-02 21:55:30 -0700817 // is the file supposed to be media-scannable?
Vasu Nori1cde3fb2010-11-05 11:02:52 -0700818 values.put(Downloads.Impl.COLUMN_MEDIA_SCANNED, (mScannable) ? SCANNABLE_VALUE_YES :
819 SCANNABLE_VALUE_NO);
Steve Howarda2709362010-07-02 17:12:48 -0700820
821 if (!mRequestHeaders.isEmpty()) {
Steve Howardea9147d2010-07-13 19:02:45 -0700822 encodeHttpHeaders(values);
Steve Howarda2709362010-07-02 17:12:48 -0700823 }
824
Vasu Norief7e33b2010-10-20 13:26:02 -0700825 putIfNonNull(values, Downloads.Impl.COLUMN_TITLE, mTitle);
826 putIfNonNull(values, Downloads.Impl.COLUMN_DESCRIPTION, mDescription);
827 putIfNonNull(values, Downloads.Impl.COLUMN_MIME_TYPE, mMimeType);
Steve Howarda2709362010-07-02 17:12:48 -0700828
Vasu Nori4c6e5df2010-10-26 17:00:16 -0700829 values.put(Downloads.Impl.COLUMN_VISIBILITY, mNotificationVisibility);
Steve Howardb8e07a52010-07-21 14:53:21 -0700830 values.put(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES, mAllowedNetworkTypes);
831 values.put(Downloads.Impl.COLUMN_ALLOW_ROAMING, mRoamingAllowed);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700832 values.put(Downloads.Impl.COLUMN_ALLOW_METERED, mMeteredAllowed);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600833 values.put(Downloads.Impl.COLUMN_FLAGS, mFlags);
Steve Howard90fb15a2010-09-09 16:13:41 -0700834 values.put(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, mIsVisibleInDownloadsUi);
Steve Howardb8e07a52010-07-21 14:53:21 -0700835
Steve Howarda2709362010-07-02 17:12:48 -0700836 return values;
837 }
838
Steve Howardea9147d2010-07-13 19:02:45 -0700839 private void encodeHttpHeaders(ContentValues values) {
840 int index = 0;
Steve Howard4f564cd2010-09-22 15:57:25 -0700841 for (Pair<String, String> header : mRequestHeaders) {
842 String headerString = header.first + ": " + header.second;
Steve Howardea9147d2010-07-13 19:02:45 -0700843 values.put(Downloads.Impl.RequestHeaders.INSERT_KEY_PREFIX + index, headerString);
844 index++;
845 }
846 }
847
Steve Howard4f564cd2010-09-22 15:57:25 -0700848 private void putIfNonNull(ContentValues contentValues, String key, Object value) {
Steve Howarda2709362010-07-02 17:12:48 -0700849 if (value != null) {
Steve Howard4f564cd2010-09-22 15:57:25 -0700850 contentValues.put(key, value.toString());
Steve Howarda2709362010-07-02 17:12:48 -0700851 }
852 }
853 }
854
855 /**
856 * This class may be used to filter download manager queries.
857 */
858 public static class Query {
Steve Howardf054e192010-09-01 18:26:26 -0700859 /**
860 * Constant for use with {@link #orderBy}
861 * @hide
862 */
863 public static final int ORDER_ASCENDING = 1;
864
865 /**
866 * Constant for use with {@link #orderBy}
867 * @hide
868 */
869 public static final int ORDER_DESCENDING = 2;
870
Steve Howard64c48b82010-10-07 17:53:52 -0700871 private long[] mIds = null;
Steve Howarda2709362010-07-02 17:12:48 -0700872 private Integer mStatusFlags = null;
Ben Lince763d82016-05-02 16:45:45 -0700873 private String mFilterString = null;
Vasu Norief7e33b2010-10-20 13:26:02 -0700874 private String mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
Steve Howardf054e192010-09-01 18:26:26 -0700875 private int mOrderDirection = ORDER_DESCENDING;
Steve Howard90fb15a2010-09-09 16:13:41 -0700876 private boolean mOnlyIncludeVisibleInDownloadsUi = false;
Steve Howarda2709362010-07-02 17:12:48 -0700877
878 /**
Steve Howard64c48b82010-10-07 17:53:52 -0700879 * Include only the downloads with the given IDs.
Steve Howarda2709362010-07-02 17:12:48 -0700880 * @return this object
881 */
Steve Howard64c48b82010-10-07 17:53:52 -0700882 public Query setFilterById(long... ids) {
883 mIds = ids;
Steve Howarda2709362010-07-02 17:12:48 -0700884 return this;
885 }
886
887 /**
Ben Lince763d82016-05-02 16:45:45 -0700888 *
889 * Include only the downloads that contains the given string in its name.
890 * @return this object
891 * @hide
892 */
893 public Query setFilterByString(@Nullable String filter) {
894 mFilterString = filter;
895 return this;
896 }
897
898 /**
Steve Howarda2709362010-07-02 17:12:48 -0700899 * Include only downloads with status matching any the given status flags.
900 * @param flags any combination of the STATUS_* bit flags
901 * @return this object
902 */
903 public Query setFilterByStatus(int flags) {
904 mStatusFlags = flags;
905 return this;
906 }
907
908 /**
Steve Howard90fb15a2010-09-09 16:13:41 -0700909 * Controls whether this query includes downloads not visible in the system's Downloads UI.
910 * @param value if true, this query will only include downloads that should be displayed in
911 * the system's Downloads UI; if false (the default), this query will include
912 * both visible and invisible downloads.
913 * @return this object
914 * @hide
915 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100916 @UnsupportedAppUsage
Steve Howard90fb15a2010-09-09 16:13:41 -0700917 public Query setOnlyIncludeVisibleInDownloadsUi(boolean value) {
918 mOnlyIncludeVisibleInDownloadsUi = value;
919 return this;
920 }
921
922 /**
Steve Howardf054e192010-09-01 18:26:26 -0700923 * Change the sort order of the returned Cursor.
924 *
925 * @param column one of the COLUMN_* constants; currently, only
926 * {@link #COLUMN_LAST_MODIFIED_TIMESTAMP} and {@link #COLUMN_TOTAL_SIZE_BYTES} are
927 * supported.
928 * @param direction either {@link #ORDER_ASCENDING} or {@link #ORDER_DESCENDING}
929 * @return this object
930 * @hide
931 */
Mathew Inwood8c854f82018-09-14 12:35:36 +0100932 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Steve Howardf054e192010-09-01 18:26:26 -0700933 public Query orderBy(String column, int direction) {
934 if (direction != ORDER_ASCENDING && direction != ORDER_DESCENDING) {
935 throw new IllegalArgumentException("Invalid direction: " + direction);
936 }
937
938 if (column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP)) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700939 mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
Steve Howardf054e192010-09-01 18:26:26 -0700940 } else if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700941 mOrderByColumn = Downloads.Impl.COLUMN_TOTAL_BYTES;
Steve Howardf054e192010-09-01 18:26:26 -0700942 } else {
943 throw new IllegalArgumentException("Cannot order by " + column);
944 }
945 mOrderDirection = direction;
946 return this;
947 }
948
949 /**
Steve Howarda2709362010-07-02 17:12:48 -0700950 * Run this query using the given ContentResolver.
951 * @param projection the projection to pass to ContentResolver.query()
952 * @return the Cursor returned by ContentResolver.query()
953 */
Steve Howardeca77fc2010-09-12 18:49:08 -0700954 Cursor runQuery(ContentResolver resolver, String[] projection, Uri baseUri) {
955 Uri uri = baseUri;
Steve Howard90fb15a2010-09-09 16:13:41 -0700956 List<String> selectionParts = new ArrayList<String>();
Steve Howard64c48b82010-10-07 17:53:52 -0700957 String[] selectionArgs = null;
Steve Howarda2709362010-07-02 17:12:48 -0700958
Ben Lince763d82016-05-02 16:45:45 -0700959 int whereArgsCount = (mIds == null) ? 0 : mIds.length;
960 whereArgsCount = (mFilterString == null) ? whereArgsCount : whereArgsCount + 1;
961 selectionArgs = new String[whereArgsCount];
962
963 if (whereArgsCount > 0) {
964 if (mIds != null) {
965 selectionParts.add(getWhereClauseForIds(mIds));
966 getWhereArgsForIds(mIds, selectionArgs);
967 }
968
969 if (mFilterString != null) {
970 selectionParts.add(Downloads.Impl.COLUMN_TITLE + " LIKE ?");
971 selectionArgs[selectionArgs.length - 1] = "%" + mFilterString + "%";
972 }
Steve Howarda2709362010-07-02 17:12:48 -0700973 }
974
975 if (mStatusFlags != null) {
976 List<String> parts = new ArrayList<String>();
977 if ((mStatusFlags & STATUS_PENDING) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700978 parts.add(statusClause("=", Downloads.Impl.STATUS_PENDING));
Steve Howarda2709362010-07-02 17:12:48 -0700979 }
980 if ((mStatusFlags & STATUS_RUNNING) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700981 parts.add(statusClause("=", Downloads.Impl.STATUS_RUNNING));
Steve Howarda2709362010-07-02 17:12:48 -0700982 }
983 if ((mStatusFlags & STATUS_PAUSED) != 0) {
Steve Howard3e8c1d32010-09-29 17:03:32 -0700984 parts.add(statusClause("=", Downloads.Impl.STATUS_PAUSED_BY_APP));
985 parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_TO_RETRY));
986 parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_FOR_NETWORK));
987 parts.add(statusClause("=", Downloads.Impl.STATUS_QUEUED_FOR_WIFI));
Steve Howarda2709362010-07-02 17:12:48 -0700988 }
989 if ((mStatusFlags & STATUS_SUCCESSFUL) != 0) {
Vasu Norief7e33b2010-10-20 13:26:02 -0700990 parts.add(statusClause("=", Downloads.Impl.STATUS_SUCCESS));
Steve Howarda2709362010-07-02 17:12:48 -0700991 }
992 if ((mStatusFlags & STATUS_FAILED) != 0) {
993 parts.add("(" + statusClause(">=", 400)
994 + " AND " + statusClause("<", 600) + ")");
995 }
Steve Howard90fb15a2010-09-09 16:13:41 -0700996 selectionParts.add(joinStrings(" OR ", parts));
Steve Howarda2709362010-07-02 17:12:48 -0700997 }
Steve Howardf054e192010-09-01 18:26:26 -0700998
Steve Howard90fb15a2010-09-09 16:13:41 -0700999 if (mOnlyIncludeVisibleInDownloadsUi) {
1000 selectionParts.add(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI + " != '0'");
1001 }
1002
Vasu Nori216fa222010-10-12 23:08:13 -07001003 // only return rows which are not marked 'deleted = 1'
1004 selectionParts.add(Downloads.Impl.COLUMN_DELETED + " != '1'");
1005
Steve Howard90fb15a2010-09-09 16:13:41 -07001006 String selection = joinStrings(" AND ", selectionParts);
Steve Howardf054e192010-09-01 18:26:26 -07001007 String orderDirection = (mOrderDirection == ORDER_ASCENDING ? "ASC" : "DESC");
1008 String orderBy = mOrderByColumn + " " + orderDirection;
1009
Steve Howard64c48b82010-10-07 17:53:52 -07001010 return resolver.query(uri, projection, selection, selectionArgs, orderBy);
Steve Howarda2709362010-07-02 17:12:48 -07001011 }
1012
1013 private String joinStrings(String joiner, Iterable<String> parts) {
1014 StringBuilder builder = new StringBuilder();
1015 boolean first = true;
1016 for (String part : parts) {
1017 if (!first) {
1018 builder.append(joiner);
1019 }
1020 builder.append(part);
1021 first = false;
1022 }
1023 return builder.toString();
1024 }
1025
1026 private String statusClause(String operator, int value) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001027 return Downloads.Impl.COLUMN_STATUS + operator + "'" + value + "'";
Steve Howarda2709362010-07-02 17:12:48 -07001028 }
1029 }
1030
Jeff Sharkey60cfad82016-01-05 17:30:57 -07001031 private final ContentResolver mResolver;
1032 private final String mPackageName;
Jeff Sharkey60cfad82016-01-05 17:30:57 -07001033
Steve Howardeca77fc2010-09-12 18:49:08 -07001034 private Uri mBaseUri = Downloads.Impl.CONTENT_URI;
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001035 private boolean mAccessFilename;
Steve Howarda2709362010-07-02 17:12:48 -07001036
1037 /**
1038 * @hide
1039 */
Jeff Sharkey60cfad82016-01-05 17:30:57 -07001040 public DownloadManager(Context context) {
1041 mResolver = context.getContentResolver();
1042 mPackageName = context.getPackageName();
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001043
1044 // Callers can access filename columns when targeting old platform
1045 // versions; otherwise we throw telling them it's deprecated.
1046 mAccessFilename = context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N;
Steve Howarda2709362010-07-02 17:12:48 -07001047 }
1048
1049 /**
Steve Howardeca77fc2010-09-12 18:49:08 -07001050 * Makes this object access the download provider through /all_downloads URIs rather than
1051 * /my_downloads URIs, for clients that have permission to do so.
1052 * @hide
1053 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001054 @UnsupportedAppUsage
Steve Howardeca77fc2010-09-12 18:49:08 -07001055 public void setAccessAllDownloads(boolean accessAllDownloads) {
1056 if (accessAllDownloads) {
1057 mBaseUri = Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI;
1058 } else {
1059 mBaseUri = Downloads.Impl.CONTENT_URI;
1060 }
1061 }
1062
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001063 /** {@hide} */
Mathew Inwood8c854f82018-09-14 12:35:36 +01001064 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001065 public void setAccessFilename(boolean accessFilename) {
1066 mAccessFilename = accessFilename;
1067 }
1068
Steve Howardeca77fc2010-09-12 18:49:08 -07001069 /**
Steve Howarda2709362010-07-02 17:12:48 -07001070 * Enqueue a new download. The download will start automatically once the download manager is
1071 * ready to execute it and connectivity is available.
1072 *
1073 * @param request the parameters specifying this download
1074 * @return an ID for the download, unique across the system. This ID is used to make future
1075 * calls related to this download.
1076 */
1077 public long enqueue(Request request) {
Steve Howardb8e07a52010-07-21 14:53:21 -07001078 ContentValues values = request.toContentValues(mPackageName);
Vasu Norief7e33b2010-10-20 13:26:02 -07001079 Uri downloadUri = mResolver.insert(Downloads.Impl.CONTENT_URI, values);
Steve Howarda2709362010-07-02 17:12:48 -07001080 long id = Long.parseLong(downloadUri.getLastPathSegment());
1081 return id;
1082 }
1083
1084 /**
Vasu Nori216fa222010-10-12 23:08:13 -07001085 * Marks the specified download as 'to be deleted'. This is done when a completed download
1086 * is to be removed but the row was stored without enough info to delete the corresponding
1087 * metadata from Mediaprovider database. Actual cleanup of this row is done in DownloadService.
1088 *
1089 * @param ids the IDs of the downloads to be marked 'deleted'
1090 * @return the number of downloads actually updated
1091 * @hide
1092 */
1093 public int markRowDeleted(long... ids) {
1094 if (ids == null || ids.length == 0) {
1095 // called with nothing to remove!
1096 throw new IllegalArgumentException("input param 'ids' can't be null");
1097 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001098 return mResolver.delete(mBaseUri, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
Vasu Nori216fa222010-10-12 23:08:13 -07001099 }
1100
1101 /**
Steve Howard64c48b82010-10-07 17:53:52 -07001102 * Cancel downloads and remove them from the download manager. Each download will be stopped if
Vasu Nori17ee56c2011-02-28 08:35:39 -08001103 * it was running, and it will no longer be accessible through the download manager.
1104 * If there is a downloaded file, partial or complete, it is deleted.
Steve Howarda2709362010-07-02 17:12:48 -07001105 *
Steve Howard64c48b82010-10-07 17:53:52 -07001106 * @param ids the IDs of the downloads to remove
1107 * @return the number of downloads actually removed
Steve Howarda2709362010-07-02 17:12:48 -07001108 */
Steve Howard64c48b82010-10-07 17:53:52 -07001109 public int remove(long... ids) {
Vasu Norie16c43b2010-11-06 18:48:08 -07001110 return markRowDeleted(ids);
Steve Howarda2709362010-07-02 17:12:48 -07001111 }
1112
1113 /**
1114 * Query the download manager about downloads that have been requested.
1115 * @param query parameters specifying filters for this query
1116 * @return a Cursor over the result set of downloads, with columns consisting of all the
1117 * COLUMN_* constants.
1118 */
1119 public Cursor query(Query query) {
Sudheer Shankae93db512019-01-11 16:05:28 -08001120 return query(query, UNDERLYING_COLUMNS);
1121 }
1122
1123 /** @hide */
1124 public Cursor query(Query query, String[] projection) {
1125 Cursor underlyingCursor = query.runQuery(mResolver, projection, mBaseUri);
Steve Howardf054e192010-09-01 18:26:26 -07001126 if (underlyingCursor == null) {
1127 return null;
1128 }
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001129 return new CursorTranslator(underlyingCursor, mBaseUri, mAccessFilename);
Steve Howarda2709362010-07-02 17:12:48 -07001130 }
1131
1132 /**
1133 * Open a downloaded file for reading. The download must have completed.
1134 * @param id the ID of the download
1135 * @return a read-only {@link ParcelFileDescriptor}
1136 * @throws FileNotFoundException if the destination file does not already exist
1137 */
1138 public ParcelFileDescriptor openDownloadedFile(long id) throws FileNotFoundException {
1139 return mResolver.openFileDescriptor(getDownloadUri(id), "r");
1140 }
1141
1142 /**
John Spurlock92a262c2013-11-04 16:25:38 -05001143 * Returns the {@link Uri} of the given downloaded file id, if the file is
1144 * downloaded successfully. Otherwise, null is returned.
Vasu Nori5be894e2010-11-02 21:55:30 -07001145 *
1146 * @param id the id of the downloaded file.
Jeff Sharkeyb11683b2015-07-29 10:15:34 -07001147 * @return the {@link Uri} of the given downloaded file id, if download was
1148 * successful. null otherwise.
Vasu Nori5be894e2010-11-02 21:55:30 -07001149 */
1150 public Uri getUriForDownloadedFile(long id) {
1151 // to check if the file is in cache, get its destination from the database
1152 Query query = new Query().setFilterById(id);
1153 Cursor cursor = null;
1154 try {
1155 cursor = query(query);
1156 if (cursor == null) {
1157 return null;
1158 }
Leon Scrogginsd75e64a2010-12-13 15:48:40 -05001159 if (cursor.moveToFirst()) {
Vasu Nori6e2b2a62010-11-16 17:58:22 -08001160 int status = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_STATUS));
Vasu Nori5be894e2010-11-02 21:55:30 -07001161 if (DownloadManager.STATUS_SUCCESSFUL == status) {
Jeff Sharkeydf42d732016-09-16 16:57:34 -06001162 return ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, id);
Vasu Nori5be894e2010-11-02 21:55:30 -07001163 }
1164 }
1165 } finally {
1166 if (cursor != null) {
1167 cursor.close();
1168 }
1169 }
1170 // downloaded file not found or its status is not 'successfully completed'
1171 return null;
1172 }
1173
1174 /**
John Spurlock92a262c2013-11-04 16:25:38 -05001175 * Returns the media type of the given downloaded file id, if the file was
1176 * downloaded successfully. Otherwise, null is returned.
Vasu Nori6e2b2a62010-11-16 17:58:22 -08001177 *
1178 * @param id the id of the downloaded file.
John Spurlock92a262c2013-11-04 16:25:38 -05001179 * @return the media type of the given downloaded file id, if download was successful. null
Vasu Nori6e2b2a62010-11-16 17:58:22 -08001180 * otherwise.
1181 */
1182 public String getMimeTypeForDownloadedFile(long id) {
1183 Query query = new Query().setFilterById(id);
1184 Cursor cursor = null;
1185 try {
1186 cursor = query(query);
1187 if (cursor == null) {
1188 return null;
1189 }
1190 while (cursor.moveToFirst()) {
1191 return cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_MEDIA_TYPE));
1192 }
1193 } finally {
1194 if (cursor != null) {
1195 cursor.close();
1196 }
1197 }
1198 // downloaded file not found or its status is not 'successfully completed'
1199 return null;
1200 }
1201
1202 /**
Steve Howard64c48b82010-10-07 17:53:52 -07001203 * Restart the given downloads, which must have already completed (successfully or not). This
Steve Howard90fb15a2010-09-09 16:13:41 -07001204 * method will only work when called from within the download manager's process.
Steve Howard64c48b82010-10-07 17:53:52 -07001205 * @param ids the IDs of the downloads
Steve Howard90fb15a2010-09-09 16:13:41 -07001206 * @hide
1207 */
Andrei Onea4b2116c2019-02-28 15:13:42 +00001208 @UnsupportedAppUsage
Steve Howard64c48b82010-10-07 17:53:52 -07001209 public void restartDownload(long... ids) {
1210 Cursor cursor = query(new Query().setFilterById(ids));
Steve Howard90fb15a2010-09-09 16:13:41 -07001211 try {
Steve Howard64c48b82010-10-07 17:53:52 -07001212 for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
1213 int status = cursor.getInt(cursor.getColumnIndex(COLUMN_STATUS));
1214 if (status != STATUS_SUCCESSFUL && status != STATUS_FAILED) {
1215 throw new IllegalArgumentException("Cannot restart incomplete download: "
1216 + cursor.getLong(cursor.getColumnIndex(COLUMN_ID)));
1217 }
Steve Howard90fb15a2010-09-09 16:13:41 -07001218 }
1219 } finally {
1220 cursor.close();
1221 }
1222
1223 ContentValues values = new ContentValues();
1224 values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, 0);
1225 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, -1);
1226 values.putNull(Downloads.Impl._DATA);
1227 values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING);
Jeff Sharkey54781202013-01-17 17:27:33 -08001228 values.put(Downloads.Impl.COLUMN_FAILED_CONNECTIONS, 0);
Steve Howard64c48b82010-10-07 17:53:52 -07001229 mResolver.update(mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
Steve Howard90fb15a2010-09-09 16:13:41 -07001230 }
1231
1232 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001233 * Force the given downloads to proceed even if their size is larger than
1234 * {@link #getMaxBytesOverMobile(Context)}.
1235 *
1236 * @hide
1237 */
1238 public void forceDownload(long... ids) {
1239 ContentValues values = new ContentValues();
1240 values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING);
1241 values.put(Downloads.Impl.COLUMN_CONTROL, Downloads.Impl.CONTROL_RUN);
1242 values.put(Downloads.Impl.COLUMN_BYPASS_RECOMMENDED_SIZE_LIMIT, 1);
1243 mResolver.update(mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
1244 }
1245
1246 /**
Vasu Nori0abbf802011-01-17 15:08:14 -08001247 * Returns maximum size, in bytes, of downloads that may go over a mobile connection; or null if
1248 * there's no limit
1249 *
1250 * @param context the {@link Context} to use for accessing the {@link ContentResolver}
1251 * @return maximum size, in bytes, of downloads that may go over a mobile connection; or null if
1252 * there's no limit
1253 */
1254 public static Long getMaxBytesOverMobile(Context context) {
1255 try {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001256 return Settings.Global.getLong(context.getContentResolver(),
1257 Settings.Global.DOWNLOAD_MAX_BYTES_OVER_MOBILE);
Vasu Nori0abbf802011-01-17 15:08:14 -08001258 } catch (SettingNotFoundException exc) {
1259 return null;
1260 }
1261 }
1262
1263 /**
Ben Lin726bf6a2016-04-27 11:38:05 -07001264 * Rename the given download if the download has completed
1265 *
1266 * @param context the {@link Context} to use in case need to update MediaProvider
1267 * @param id the downloaded id
1268 * @param displayName the new name to rename to
1269 * @return true if rename was successful, false otherwise
1270 * @hide
1271 */
1272 public boolean rename(Context context, long id, String displayName) {
1273 if (!FileUtils.isValidFatFilename(displayName)) {
1274 throw new SecurityException(displayName + " is not a valid filename");
1275 }
1276
Sudheer Shankac4229172019-04-25 17:52:10 -07001277 final String filePath;
1278 final Query query = new Query().setFilterById(id);
1279 try (Cursor cursor = query(query)) {
Ben Lin726bf6a2016-04-27 11:38:05 -07001280 if (cursor == null) {
Sudheer Shankac4229172019-04-25 17:52:10 -07001281 throw new IllegalStateException("Missing cursor for download id=" + id);
Ben Lin726bf6a2016-04-27 11:38:05 -07001282 }
1283 if (cursor.moveToFirst()) {
Sudheer Shankac4229172019-04-25 17:52:10 -07001284 final int status = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_STATUS));
1285 if (status != DownloadManager.STATUS_SUCCESSFUL) {
1286 throw new IllegalStateException("Download is not completed yet: "
1287 + DatabaseUtils.dumpCurrentRowToString(cursor));
Ben Lin726bf6a2016-04-27 11:38:05 -07001288 }
Sudheer Shankac4229172019-04-25 17:52:10 -07001289 filePath = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_LOCAL_FILENAME));
1290 if (filePath == null) {
1291 throw new IllegalStateException("Download doesn't have a valid file path: "
1292 + DatabaseUtils.dumpCurrentRowToString(cursor));
1293 } else if (!new File(filePath).exists()) {
1294 throw new IllegalStateException("Downloaded file doesn't exist anymore: "
1295 + DatabaseUtils.dumpCurrentRowToString(cursor));
1296 }
1297 } else {
1298 throw new IllegalStateException("Missing download id=" + id);
Ben Lin726bf6a2016-04-27 11:38:05 -07001299 }
1300 }
1301
Sudheer Shankac4229172019-04-25 17:52:10 -07001302 final File before = new File(filePath);
1303 final File after = new File(before.getParentFile(), displayName);
Ben Lin726bf6a2016-04-27 11:38:05 -07001304
1305 if (after.exists()) {
Sudheer Shankac4229172019-04-25 17:52:10 -07001306 throw new IllegalStateException("File already exists: " + after);
Ben Lin726bf6a2016-04-27 11:38:05 -07001307 }
1308 if (!before.renameTo(after)) {
Sudheer Shankac4229172019-04-25 17:52:10 -07001309 throw new IllegalStateException(
1310 "Failed to rename file from " + before + " to " + after);
Ben Lin726bf6a2016-04-27 11:38:05 -07001311 }
1312
Sudheer Shankac0ff9082019-05-23 10:47:30 -07001313 // TODO: DownloadProvider.update() should take care of updating corresponding
1314 // MediaProvider entries.
1315 MediaStore.scanFile(context, before);
1316 MediaStore.scanFile(context, after);
1317
Sudheer Shankac4229172019-04-25 17:52:10 -07001318 final ContentValues values = new ContentValues();
Ben Lin726bf6a2016-04-27 11:38:05 -07001319 values.put(Downloads.Impl.COLUMN_TITLE, displayName);
1320 values.put(Downloads.Impl._DATA, after.toString());
1321 values.putNull(Downloads.Impl.COLUMN_MEDIAPROVIDER_URI);
Sudheer Shankac4229172019-04-25 17:52:10 -07001322 final long[] ids = { id };
Ben Lin726bf6a2016-04-27 11:38:05 -07001323
Sudheer Shankac4229172019-04-25 17:52:10 -07001324 return mResolver.update(
1325 mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids)) == 1;
Ben Lin726bf6a2016-04-27 11:38:05 -07001326 }
1327
1328 /**
Vasu Nori0abbf802011-01-17 15:08:14 -08001329 * Returns recommended maximum size, in bytes, of downloads that may go over a mobile
1330 * connection; or null if there's no recommended limit. The user will have the option to bypass
1331 * this limit.
1332 *
1333 * @param context the {@link Context} to use for accessing the {@link ContentResolver}
1334 * @return recommended maximum size, in bytes, of downloads that may go over a mobile
1335 * connection; or null if there's no recommended limit.
1336 */
1337 public static Long getRecommendedMaxBytesOverMobile(Context context) {
1338 try {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001339 return Settings.Global.getLong(context.getContentResolver(),
1340 Settings.Global.DOWNLOAD_RECOMMENDED_MAX_BYTES_OVER_MOBILE);
Vasu Nori0abbf802011-01-17 15:08:14 -08001341 } catch (SettingNotFoundException exc) {
1342 return null;
1343 }
1344 }
Vasu Noric0e50752011-01-20 17:57:54 -08001345
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001346 /** {@hide} */
1347 public static boolean isActiveNetworkExpensive(Context context) {
1348 // TODO: connect to NetworkPolicyManager
1349 return false;
1350 }
1351
1352 /** {@hide} */
1353 public static long getActiveNetworkWarningBytes(Context context) {
1354 // TODO: connect to NetworkPolicyManager
1355 return -1;
1356 }
1357
Vasu Noric0e50752011-01-20 17:57:54 -08001358 /**
1359 * Adds a file to the downloads database system, so it could appear in Downloads App
1360 * (and thus become eligible for management by the Downloads App).
1361 * <p>
1362 * It is helpful to make the file scannable by MediaScanner by setting the param
1363 * isMediaScannerScannable to true. It makes the file visible in media managing
1364 * applications such as Gallery App, which could be a useful purpose of using this API.
1365 *
Sudheer Shanka25f1c6e2019-04-22 17:03:47 -07001366 * <p> For applications targeting {@link android.os.Build.VERSION_CODES#Q} or above,
1367 * {@code path} must be within directories owned by the application
1368 * {e.g. {@link Context#getExternalFilesDir(String)}} or if the application is running under
1369 * the legacy storage model (see
1370 * {@link android.R.styleable#AndroidManifestApplication_requestLegacyExternalStorage
1371 * android:requestLegacyExternalStorage}), {@code path} can also be within the top-level
1372 * Downloads directory (as returned by
1373 * {@link Environment#getExternalStoragePublicDirectory(String)} with
1374 * {@link Environment#DIRECTORY_DOWNLOADS}).
1375 *
Vasu Noric0e50752011-01-20 17:57:54 -08001376 * @param title the title that would appear for this file in Downloads App.
1377 * @param description the description that would appear for this file in Downloads App.
1378 * @param isMediaScannerScannable true if the file is to be scanned by MediaScanner. Files
1379 * scanned by MediaScanner appear in the applications used to view media (for example,
Sudheer Shanka684c02a2019-01-29 17:41:15 -08001380 * Gallery app).
Vasu Noric0e50752011-01-20 17:57:54 -08001381 * @param mimeType mimetype of the file.
1382 * @param path absolute pathname to the file. The file should be world-readable, so that it can
1383 * be managed by the Downloads App and any other app that is used to read it (for example,
1384 * Gallery app to display the file, if the file contents represent a video/image).
1385 * @param length length of the downloaded file
Vasu Norif9e85232011-02-10 14:59:54 -08001386 * @param showNotification true if a notification is to be sent, false otherwise
Vasu Noric0e50752011-01-20 17:57:54 -08001387 * @return an ID for the download entry added to the downloads app, unique across the system
1388 * This ID is used to make future calls related to this download.
Sudheer Shanka0b70c2a2019-04-27 19:13:33 -07001389 *
1390 * @deprecated Apps should instead contribute files to
1391 * {@link android.provider.MediaStore.Downloads} collection to make them available to user
1392 * as part of Downloads.
Vasu Noric0e50752011-01-20 17:57:54 -08001393 */
Sudheer Shanka0b70c2a2019-04-27 19:13:33 -07001394 @Deprecated
Vasu Nori37281302011-03-07 11:25:01 -08001395 public long addCompletedDownload(String title, String description,
Vasu Norif9e85232011-02-10 14:59:54 -08001396 boolean isMediaScannerScannable, String mimeType, String path, long length,
1397 boolean showNotification) {
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001398 return addCompletedDownload(title, description, isMediaScannerScannable, mimeType, path,
Edward Cunninghamabb2c5a2016-03-25 20:56:31 +00001399 length, showNotification, false, null, null);
1400 }
1401
1402 /**
1403 * Adds a file to the downloads database system, so it could appear in Downloads App
1404 * (and thus become eligible for management by the Downloads App).
1405 * <p>
1406 * It is helpful to make the file scannable by MediaScanner by setting the param
1407 * isMediaScannerScannable to true. It makes the file visible in media managing
1408 * applications such as Gallery App, which could be a useful purpose of using this API.
1409 *
Sudheer Shanka25f1c6e2019-04-22 17:03:47 -07001410 * <p> For applications targeting {@link android.os.Build.VERSION_CODES#Q} or above,
1411 * {@code path} must be within directories owned by the application
1412 * {e.g. {@link Context#getExternalFilesDir(String)}} or if the application is running under
1413 * the legacy storage model (see
1414 * {@link android.R.styleable#AndroidManifestApplication_requestLegacyExternalStorage
1415 * android:requestLegacyExternalStorage}), {@code path} can also be within the top-level
1416 * Downloads directory (as returned by
1417 * {@link Environment#getExternalStoragePublicDirectory(String)} with
1418 * {@link Environment#DIRECTORY_DOWNLOADS}).
1419 *
Edward Cunninghamabb2c5a2016-03-25 20:56:31 +00001420 * @param title the title that would appear for this file in Downloads App.
1421 * @param description the description that would appear for this file in Downloads App.
1422 * @param isMediaScannerScannable true if the file is to be scanned by MediaScanner. Files
1423 * scanned by MediaScanner appear in the applications used to view media (for example,
Sudheer Shanka684c02a2019-01-29 17:41:15 -08001424 * Gallery app).
Edward Cunninghamabb2c5a2016-03-25 20:56:31 +00001425 * @param mimeType mimetype of the file.
1426 * @param path absolute pathname to the file. The file should be world-readable, so that it can
1427 * be managed by the Downloads App and any other app that is used to read it (for example,
1428 * Gallery app to display the file, if the file contents represent a video/image).
1429 * @param length length of the downloaded file
1430 * @param showNotification true if a notification is to be sent, false otherwise
1431 * @param uri the original HTTP URI of the download
1432 * @param referer the HTTP Referer for the download
1433 * @return an ID for the download entry added to the downloads app, unique across the system
1434 * This ID is used to make future calls related to this download.
Sudheer Shanka0b70c2a2019-04-27 19:13:33 -07001435 *
1436 * @deprecated Apps should instead contribute files to
1437 * {@link android.provider.MediaStore.Downloads} collection to make them available to user
1438 * as part of Downloads.
Edward Cunninghamabb2c5a2016-03-25 20:56:31 +00001439 */
Sudheer Shanka0b70c2a2019-04-27 19:13:33 -07001440 @Deprecated
Edward Cunninghamabb2c5a2016-03-25 20:56:31 +00001441 public long addCompletedDownload(String title, String description,
1442 boolean isMediaScannerScannable, String mimeType, String path, long length,
1443 boolean showNotification, Uri uri, Uri referer) {
1444 return addCompletedDownload(title, description, isMediaScannerScannable, mimeType, path,
1445 length, showNotification, false, uri, referer);
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001446 }
1447
Sudheer Shanka25f1c6e2019-04-22 17:03:47 -07001448 /**
1449 * <p> For applications targeting {@link android.os.Build.VERSION_CODES#Q} or above,
1450 * {@code path} must be within directories owned by the application
1451 * {e.g. {@link Context#getExternalFilesDir(String)}} or if the application is running under
1452 * the legacy storage model (see
1453 * {@link android.R.styleable#AndroidManifestApplication_requestLegacyExternalStorage
1454 * android:requestLegacyExternalStorage}), {@code path} can also be within the top-level
1455 * Downloads directory (as returned by
1456 * {@link Environment#getExternalStoragePublicDirectory(String)} with
1457 * {@link Environment#DIRECTORY_DOWNLOADS}).
1458 *
Sudheer Shanka0b70c2a2019-04-27 19:13:33 -07001459 * @deprecated Apps should instead contribute files to
1460 * {@link android.provider.MediaStore.Downloads} collection to make them available to user
1461 * as part of Downloads.
1462 *
Sudheer Shanka25f1c6e2019-04-22 17:03:47 -07001463 * {@hide}
1464 */
Sudheer Shanka0b70c2a2019-04-27 19:13:33 -07001465 @Deprecated
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001466 public long addCompletedDownload(String title, String description,
1467 boolean isMediaScannerScannable, String mimeType, String path, long length,
1468 boolean showNotification, boolean allowWrite) {
Edward Cunninghamabb2c5a2016-03-25 20:56:31 +00001469 return addCompletedDownload(title, description, isMediaScannerScannable, mimeType, path,
1470 length, showNotification, allowWrite, null, null);
1471 }
1472
Sudheer Shanka25f1c6e2019-04-22 17:03:47 -07001473 /**
1474 * <p> For applications targeting {@link android.os.Build.VERSION_CODES#Q} or above,
1475 * {@code path} must be within directories owned by the application
1476 * {e.g. {@link Context#getExternalFilesDir(String)}} or if the application is running under
1477 * the legacy storage model (see
1478 * {@link android.R.styleable#AndroidManifestApplication_requestLegacyExternalStorage
1479 * android:requestLegacyExternalStorage}), {@code path} can also be within the top-level
1480 * Downloads directory (as returned by
1481 * {@link Environment#getExternalStoragePublicDirectory(String)} with
1482 * {@link Environment#DIRECTORY_DOWNLOADS}).
1483 *
1484 * {@hide}
Sudheer Shanka0b70c2a2019-04-27 19:13:33 -07001485 *
1486 * @deprecated Apps should instead contribute files to
1487 * {@link android.provider.MediaStore.Downloads} collection to make them available to user
1488 * as part of Downloads.
Sudheer Shanka25f1c6e2019-04-22 17:03:47 -07001489 */
Sudheer Shanka0b70c2a2019-04-27 19:13:33 -07001490 @Deprecated
Edward Cunninghamabb2c5a2016-03-25 20:56:31 +00001491 public long addCompletedDownload(String title, String description,
1492 boolean isMediaScannerScannable, String mimeType, String path, long length,
1493 boolean showNotification, boolean allowWrite, Uri uri, Uri referer) {
Vasu Noric0e50752011-01-20 17:57:54 -08001494 // make sure the input args are non-null/non-zero
1495 validateArgumentIsNonEmpty("title", title);
1496 validateArgumentIsNonEmpty("description", description);
1497 validateArgumentIsNonEmpty("path", path);
1498 validateArgumentIsNonEmpty("mimeType", mimeType);
Jeff Sharkey33f95ed2012-05-02 17:07:54 -07001499 if (length < 0) {
Vasu Noric0e50752011-01-20 17:57:54 -08001500 throw new IllegalArgumentException(" invalid value for param: totalBytes");
1501 }
1502
1503 // if there is already an entry with the given path name in downloads.db, return its id
Edward Cunninghamabb2c5a2016-03-25 20:56:31 +00001504 Request request;
1505 if (uri != null) {
1506 request = new Request(uri);
1507 } else {
1508 request = new Request(NON_DOWNLOADMANAGER_DOWNLOAD);
1509 }
1510 request.setTitle(title)
Vasu Noric0e50752011-01-20 17:57:54 -08001511 .setDescription(description)
1512 .setMimeType(mimeType);
Edward Cunninghamabb2c5a2016-03-25 20:56:31 +00001513 if (referer != null) {
1514 request.addRequestHeader("Referer", referer.toString());
1515 }
Vasu Noric0e50752011-01-20 17:57:54 -08001516 ContentValues values = request.toContentValues(null);
1517 values.put(Downloads.Impl.COLUMN_DESTINATION,
1518 Downloads.Impl.DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD);
1519 values.put(Downloads.Impl._DATA, path);
1520 values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_SUCCESS);
1521 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, length);
1522 values.put(Downloads.Impl.COLUMN_MEDIA_SCANNED,
1523 (isMediaScannerScannable) ? Request.SCANNABLE_VALUE_YES :
1524 Request.SCANNABLE_VALUE_NO);
Vasu Norif9e85232011-02-10 14:59:54 -08001525 values.put(Downloads.Impl.COLUMN_VISIBILITY, (showNotification) ?
1526 Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION : Request.VISIBILITY_HIDDEN);
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001527 values.put(Downloads.Impl.COLUMN_ALLOW_WRITE, allowWrite ? 1 : 0);
Vasu Noric0e50752011-01-20 17:57:54 -08001528 Uri downloadUri = mResolver.insert(Downloads.Impl.CONTENT_URI, values);
1529 if (downloadUri == null) {
1530 return -1;
1531 }
1532 return Long.parseLong(downloadUri.getLastPathSegment());
1533 }
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001534
Vasu Noric0e50752011-01-20 17:57:54 -08001535 private static final String NON_DOWNLOADMANAGER_DOWNLOAD =
1536 "non-dwnldmngr-download-dont-retry2download";
1537
1538 private static void validateArgumentIsNonEmpty(String paramName, String val) {
1539 if (TextUtils.isEmpty(val)) {
1540 throw new IllegalArgumentException(paramName + " can't be null");
1541 }
1542 }
1543
Vasu Nori0abbf802011-01-17 15:08:14 -08001544 /**
Steve Howarda2709362010-07-02 17:12:48 -07001545 * Get the DownloadProvider URI for the download with the given ID.
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001546 *
1547 * @hide
Steve Howarda2709362010-07-02 17:12:48 -07001548 */
Jeff Sharkeyb180a652013-09-23 14:23:41 -07001549 public Uri getDownloadUri(long id) {
Jeff Sharkey15471942016-09-16 12:04:05 -06001550 return ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, id);
Steve Howarda2709362010-07-02 17:12:48 -07001551 }
1552
1553 /**
Steve Howard64c48b82010-10-07 17:53:52 -07001554 * Get a parameterized SQL WHERE clause to select a bunch of IDs.
1555 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001556 @UnsupportedAppUsage
Steve Howard64c48b82010-10-07 17:53:52 -07001557 static String getWhereClauseForIds(long[] ids) {
1558 StringBuilder whereClause = new StringBuilder();
Vasu Norie7be6bd2010-10-10 14:58:08 -07001559 whereClause.append("(");
Steve Howard64c48b82010-10-07 17:53:52 -07001560 for (int i = 0; i < ids.length; i++) {
1561 if (i > 0) {
Vasu Norie7be6bd2010-10-10 14:58:08 -07001562 whereClause.append("OR ");
Steve Howard64c48b82010-10-07 17:53:52 -07001563 }
Vasu Norie7be6bd2010-10-10 14:58:08 -07001564 whereClause.append(Downloads.Impl._ID);
1565 whereClause.append(" = ? ");
Steve Howard64c48b82010-10-07 17:53:52 -07001566 }
1567 whereClause.append(")");
1568 return whereClause.toString();
1569 }
1570
1571 /**
1572 * Get the selection args for a clause returned by {@link #getWhereClauseForIds(long[])}.
1573 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +01001574 @UnsupportedAppUsage
Steve Howard64c48b82010-10-07 17:53:52 -07001575 static String[] getWhereArgsForIds(long[] ids) {
1576 String[] whereArgs = new String[ids.length];
Ben Lince763d82016-05-02 16:45:45 -07001577 return getWhereArgsForIds(ids, whereArgs);
Steve Howard64c48b82010-10-07 17:53:52 -07001578 }
1579
1580 /**
Ben Lince763d82016-05-02 16:45:45 -07001581 * Get selection args for a clause returned by {@link #getWhereClauseForIds(long[])}
1582 * and write it to the supplied args array.
1583 */
1584 static String[] getWhereArgsForIds(long[] ids, String[] args) {
1585 assert(args.length >= ids.length);
1586 for (int i = 0; i < ids.length; i++) {
1587 args[i] = Long.toString(ids[i]);
1588 }
1589 return args;
1590 }
1591
1592
1593 /**
Steve Howarda2709362010-07-02 17:12:48 -07001594 * This class wraps a cursor returned by DownloadProvider -- the "underlying cursor" -- and
1595 * presents a different set of columns, those defined in the DownloadManager.COLUMN_* constants.
1596 * Some columns correspond directly to underlying values while others are computed from
1597 * underlying data.
1598 */
1599 private static class CursorTranslator extends CursorWrapper {
Jeff Sharkey60cfad82016-01-05 17:30:57 -07001600 private final Uri mBaseUri;
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001601 private final boolean mAccessFilename;
Steve Howardeca77fc2010-09-12 18:49:08 -07001602
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001603 public CursorTranslator(Cursor cursor, Uri baseUri, boolean accessFilename) {
Steve Howarda2709362010-07-02 17:12:48 -07001604 super(cursor);
Steve Howardeca77fc2010-09-12 18:49:08 -07001605 mBaseUri = baseUri;
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001606 mAccessFilename = accessFilename;
Steve Howarda2709362010-07-02 17:12:48 -07001607 }
1608
1609 @Override
Steve Howarda2709362010-07-02 17:12:48 -07001610 public int getInt(int columnIndex) {
1611 return (int) getLong(columnIndex);
1612 }
1613
1614 @Override
1615 public long getLong(int columnIndex) {
Vasu Norie16c43b2010-11-06 18:48:08 -07001616 if (getColumnName(columnIndex).equals(COLUMN_REASON)) {
1617 return getReason(super.getInt(getColumnIndex(Downloads.Impl.COLUMN_STATUS)));
1618 } else if (getColumnName(columnIndex).equals(COLUMN_STATUS)) {
1619 return translateStatus(super.getInt(getColumnIndex(Downloads.Impl.COLUMN_STATUS)));
1620 } else {
1621 return super.getLong(columnIndex);
1622 }
Steve Howarda2709362010-07-02 17:12:48 -07001623 }
1624
1625 @Override
1626 public String getString(int columnIndex) {
Jeff Sharkey60cfad82016-01-05 17:30:57 -07001627 final String columnName = getColumnName(columnIndex);
1628 switch (columnName) {
1629 case COLUMN_LOCAL_URI:
1630 return getLocalUri();
1631 case COLUMN_LOCAL_FILENAME:
Jeff Sharkeyaec99bf2016-01-07 09:58:40 -07001632 if (!mAccessFilename) {
Jeff Sharkey0c2ccd02016-03-22 10:05:47 -06001633 throw new SecurityException(
Jeff Sharkey60cfad82016-01-05 17:30:57 -07001634 "COLUMN_LOCAL_FILENAME is deprecated;"
1635 + " use ContentResolver.openFileDescriptor() instead");
1636 }
1637 default:
1638 return super.getString(columnIndex);
1639 }
Steve Howardeca77fc2010-09-12 18:49:08 -07001640 }
1641
1642 private String getLocalUri() {
Vasu Norie16c43b2010-11-06 18:48:08 -07001643 long destinationType = getLong(getColumnIndex(Downloads.Impl.COLUMN_DESTINATION));
1644 if (destinationType == Downloads.Impl.DESTINATION_FILE_URI ||
Vasu Noric0e50752011-01-20 17:57:54 -08001645 destinationType == Downloads.Impl.DESTINATION_EXTERNAL ||
1646 destinationType == Downloads.Impl.DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD) {
Jeff Sharkey281c1822016-03-30 19:46:42 -06001647 String localPath = super.getString(getColumnIndex(COLUMN_LOCAL_FILENAME));
Steve Howard99047d72010-09-29 17:41:37 -07001648 if (localPath == null) {
1649 return null;
1650 }
1651 return Uri.fromFile(new File(localPath)).toString();
Steve Howardbb0d23b2010-09-22 18:56:29 -07001652 }
1653
Steve Howardeca77fc2010-09-12 18:49:08 -07001654 // return content URI for cache download
Vasu Norie16c43b2010-11-06 18:48:08 -07001655 long downloadId = getLong(getColumnIndex(Downloads.Impl._ID));
Jeff Sharkey15471942016-09-16 12:04:05 -06001656 return ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, downloadId).toString();
Steve Howarda2709362010-07-02 17:12:48 -07001657 }
1658
Steve Howard3e8c1d32010-09-29 17:03:32 -07001659 private long getReason(int status) {
1660 switch (translateStatus(status)) {
1661 case STATUS_FAILED:
1662 return getErrorCode(status);
1663
1664 case STATUS_PAUSED:
1665 return getPausedReason(status);
1666
1667 default:
1668 return 0; // arbitrary value when status is not an error
Steve Howarda2709362010-07-02 17:12:48 -07001669 }
Steve Howard3e8c1d32010-09-29 17:03:32 -07001670 }
1671
1672 private long getPausedReason(int status) {
1673 switch (status) {
1674 case Downloads.Impl.STATUS_WAITING_TO_RETRY:
1675 return PAUSED_WAITING_TO_RETRY;
1676
1677 case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
1678 return PAUSED_WAITING_FOR_NETWORK;
1679
1680 case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
1681 return PAUSED_QUEUED_FOR_WIFI;
1682
1683 default:
1684 return PAUSED_UNKNOWN;
1685 }
1686 }
1687
1688 private long getErrorCode(int status) {
Steve Howard33bbd122010-08-02 17:51:29 -07001689 if ((400 <= status && status < Downloads.Impl.MIN_ARTIFICIAL_ERROR_STATUS)
1690 || (500 <= status && status < 600)) {
Steve Howarda2709362010-07-02 17:12:48 -07001691 // HTTP status code
1692 return status;
1693 }
1694
1695 switch (status) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001696 case Downloads.Impl.STATUS_FILE_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001697 return ERROR_FILE_ERROR;
1698
Vasu Norief7e33b2010-10-20 13:26:02 -07001699 case Downloads.Impl.STATUS_UNHANDLED_HTTP_CODE:
1700 case Downloads.Impl.STATUS_UNHANDLED_REDIRECT:
Steve Howarda2709362010-07-02 17:12:48 -07001701 return ERROR_UNHANDLED_HTTP_CODE;
1702
Vasu Norief7e33b2010-10-20 13:26:02 -07001703 case Downloads.Impl.STATUS_HTTP_DATA_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001704 return ERROR_HTTP_DATA_ERROR;
1705
Vasu Norief7e33b2010-10-20 13:26:02 -07001706 case Downloads.Impl.STATUS_TOO_MANY_REDIRECTS:
Steve Howarda2709362010-07-02 17:12:48 -07001707 return ERROR_TOO_MANY_REDIRECTS;
1708
Vasu Norief7e33b2010-10-20 13:26:02 -07001709 case Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001710 return ERROR_INSUFFICIENT_SPACE;
1711
Vasu Norief7e33b2010-10-20 13:26:02 -07001712 case Downloads.Impl.STATUS_DEVICE_NOT_FOUND_ERROR:
Steve Howarda2709362010-07-02 17:12:48 -07001713 return ERROR_DEVICE_NOT_FOUND;
1714
Steve Howard33bbd122010-08-02 17:51:29 -07001715 case Downloads.Impl.STATUS_CANNOT_RESUME:
1716 return ERROR_CANNOT_RESUME;
1717
Steve Howarda9e87c92010-09-16 12:02:03 -07001718 case Downloads.Impl.STATUS_FILE_ALREADY_EXISTS_ERROR:
1719 return ERROR_FILE_ALREADY_EXISTS;
1720
Steve Howarda2709362010-07-02 17:12:48 -07001721 default:
1722 return ERROR_UNKNOWN;
1723 }
1724 }
1725
Steve Howard3e8c1d32010-09-29 17:03:32 -07001726 private int translateStatus(int status) {
Steve Howarda2709362010-07-02 17:12:48 -07001727 switch (status) {
Vasu Norief7e33b2010-10-20 13:26:02 -07001728 case Downloads.Impl.STATUS_PENDING:
Steve Howarda2709362010-07-02 17:12:48 -07001729 return STATUS_PENDING;
1730
Vasu Norief7e33b2010-10-20 13:26:02 -07001731 case Downloads.Impl.STATUS_RUNNING:
Steve Howarda2709362010-07-02 17:12:48 -07001732 return STATUS_RUNNING;
1733
Steve Howard3e8c1d32010-09-29 17:03:32 -07001734 case Downloads.Impl.STATUS_PAUSED_BY_APP:
1735 case Downloads.Impl.STATUS_WAITING_TO_RETRY:
1736 case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
1737 case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
Steve Howarda2709362010-07-02 17:12:48 -07001738 return STATUS_PAUSED;
1739
Vasu Norief7e33b2010-10-20 13:26:02 -07001740 case Downloads.Impl.STATUS_SUCCESS:
Steve Howarda2709362010-07-02 17:12:48 -07001741 return STATUS_SUCCESSFUL;
1742
1743 default:
Vasu Norief7e33b2010-10-20 13:26:02 -07001744 assert Downloads.Impl.isStatusError(status);
Steve Howarda2709362010-07-02 17:12:48 -07001745 return STATUS_FAILED;
1746 }
1747 }
1748 }
1749}