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