OSDN Git Service

RESTRICT AUTOMERGE Enable stricter SQLiteQueryBuilder options.
[android-x86/frameworks-base.git] / core / java / android / app / DownloadManager.java
1 /*
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
17 package android.app;
18
19 import android.annotation.Nullable;
20 import android.annotation.SdkConstant;
21 import android.annotation.SdkConstant.SdkConstantType;
22 import android.content.ContentResolver;
23 import android.content.ContentUris;
24 import android.content.ContentValues;
25 import android.content.Context;
26 import android.content.Intent;
27 import android.database.Cursor;
28 import android.database.CursorWrapper;
29 import android.net.ConnectivityManager;
30 import android.net.NetworkPolicyManager;
31 import android.net.Uri;
32 import android.os.Build;
33 import android.os.Environment;
34 import android.os.FileUtils;
35 import android.os.ParcelFileDescriptor;
36 import android.provider.Downloads;
37 import android.provider.Settings;
38 import android.provider.MediaStore.Images;
39 import android.provider.Settings.SettingNotFoundException;
40 import android.text.TextUtils;
41 import android.util.Pair;
42
43 import java.io.File;
44 import java.io.FileNotFoundException;
45 import java.util.ArrayList;
46 import java.util.List;
47
48 /**
49  * The download manager is a system service that handles long-running HTTP downloads. Clients may
50  * request that a URI be downloaded to a particular destination file. The download manager will
51  * conduct the download in the background, taking care of HTTP interactions and retrying downloads
52  * after failures or across connectivity changes and system reboots.
53  *
54  * Instances of this class should be obtained through
55  * {@link android.content.Context#getSystemService(String)} by passing
56  * {@link android.content.Context#DOWNLOAD_SERVICE}.
57  *
58  * Apps that request downloads through this API should register a broadcast receiver for
59  * {@link #ACTION_NOTIFICATION_CLICKED} to appropriately handle when the user clicks on a running
60  * download in a notification or from the downloads UI.
61  *
62  * Note that the application must have the {@link android.Manifest.permission#INTERNET}
63  * permission to use this class.
64  */
65 public class DownloadManager {
66
67     /**
68      * An identifier for a particular download, unique across the system.  Clients use this ID to
69      * make subsequent calls related to the download.
70      */
71     public final static String COLUMN_ID = Downloads.Impl._ID;
72
73     /**
74      * The client-supplied title for this download.  This will be displayed in system notifications.
75      * Defaults to the empty string.
76      */
77     public final static String COLUMN_TITLE = Downloads.Impl.COLUMN_TITLE;
78
79     /**
80      * The client-supplied description of this download.  This will be displayed in system
81      * notifications.  Defaults to the empty string.
82      */
83     public final static String COLUMN_DESCRIPTION = Downloads.Impl.COLUMN_DESCRIPTION;
84
85     /**
86      * URI to be downloaded.
87      */
88     public final static String COLUMN_URI = Downloads.Impl.COLUMN_URI;
89
90     /**
91      * Internet Media Type of the downloaded file.  If no value is provided upon creation, this will
92      * initially be null and will be filled in based on the server's response once the download has
93      * started.
94      *
95      * @see <a href="http://www.ietf.org/rfc/rfc1590.txt">RFC 1590, defining Media Types</a>
96      */
97     public final static String COLUMN_MEDIA_TYPE = "media_type";
98
99     /**
100      * Total size of the download in bytes.  This will initially be -1 and will be filled in once
101      * the download starts.
102      */
103     public final static String COLUMN_TOTAL_SIZE_BYTES = "total_size";
104
105     /**
106      * Uri where downloaded file will be stored.  If a destination is supplied by client, that URI
107      * will be used here.  Otherwise, the value will initially be null and will be filled in with a
108      * generated URI once the download has started.
109      */
110     public final static String COLUMN_LOCAL_URI = "local_uri";
111
112     /**
113      * Path to the downloaded file on disk.
114      * <p>
115      * Note that apps may not have filesystem permissions to directly access
116      * this path. Instead of trying to open this path directly, apps should use
117      * {@link ContentResolver#openFileDescriptor(Uri, String)} to gain access.
118      *
119      * @deprecated apps should transition to using
120      *             {@link ContentResolver#openFileDescriptor(Uri, String)}
121      *             instead.
122      */
123     @Deprecated
124     public final static String COLUMN_LOCAL_FILENAME = "local_filename";
125
126     /**
127      * Current status of the download, as one of the STATUS_* constants.
128      */
129     public final static String COLUMN_STATUS = Downloads.Impl.COLUMN_STATUS;
130
131     /** {@hide} */
132     public static final String COLUMN_FILE_NAME_HINT = Downloads.Impl.COLUMN_FILE_NAME_HINT;
133
134     /**
135      * Provides more detail on the status of the download.  Its meaning depends on the value of
136      * {@link #COLUMN_STATUS}.
137      *
138      * When {@link #COLUMN_STATUS} is {@link #STATUS_FAILED}, this indicates the type of error that
139      * occurred.  If an HTTP error occurred, this will hold the HTTP status code as defined in RFC
140      * 2616.  Otherwise, it will hold one of the ERROR_* constants.
141      *
142      * When {@link #COLUMN_STATUS} is {@link #STATUS_PAUSED}, this indicates why the download is
143      * paused.  It will hold one of the PAUSED_* constants.
144      *
145      * If {@link #COLUMN_STATUS} is neither {@link #STATUS_FAILED} nor {@link #STATUS_PAUSED}, this
146      * column's value is undefined.
147      *
148      * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1.1">RFC 2616
149      * status codes</a>
150      */
151     public final static String COLUMN_REASON = "reason";
152
153     /**
154      * Number of bytes download so far.
155      */
156     public final static String COLUMN_BYTES_DOWNLOADED_SO_FAR = "bytes_so_far";
157
158     /**
159      * Timestamp when the download was last modified, in {@link System#currentTimeMillis
160      * System.currentTimeMillis()} (wall clock time in UTC).
161      */
162     public final static String COLUMN_LAST_MODIFIED_TIMESTAMP = "last_modified_timestamp";
163
164     /**
165      * The URI to the corresponding entry in MediaProvider for this downloaded entry. It is
166      * used to delete the entries from MediaProvider database when it is deleted from the
167      * downloaded list.
168      */
169     public static final String COLUMN_MEDIAPROVIDER_URI = Downloads.Impl.COLUMN_MEDIAPROVIDER_URI;
170
171     /** {@hide} */
172     public static final String COLUMN_DESTINATION = Downloads.Impl.COLUMN_DESTINATION;
173
174     /**
175      * @hide
176      */
177     public final static String COLUMN_ALLOW_WRITE = Downloads.Impl.COLUMN_ALLOW_WRITE;
178
179     /**
180      * Value of {@link #COLUMN_STATUS} when the download is waiting to start.
181      */
182     public final static int STATUS_PENDING = 1 << 0;
183
184     /**
185      * Value of {@link #COLUMN_STATUS} when the download is currently running.
186      */
187     public final static int STATUS_RUNNING = 1 << 1;
188
189     /**
190      * Value of {@link #COLUMN_STATUS} when the download is waiting to retry or resume.
191      */
192     public final static int STATUS_PAUSED = 1 << 2;
193
194     /**
195      * Value of {@link #COLUMN_STATUS} when the download has successfully completed.
196      */
197     public final static int STATUS_SUCCESSFUL = 1 << 3;
198
199     /**
200      * Value of {@link #COLUMN_STATUS} when the download has failed (and will not be retried).
201      */
202     public final static int STATUS_FAILED = 1 << 4;
203
204     /**
205      * Value of COLUMN_ERROR_CODE when the download has completed with an error that doesn't fit
206      * under any other error code.
207      */
208     public final static int ERROR_UNKNOWN = 1000;
209
210     /**
211      * Value of {@link #COLUMN_REASON} when a storage issue arises which doesn't fit under any
212      * other error code. Use the more specific {@link #ERROR_INSUFFICIENT_SPACE} and
213      * {@link #ERROR_DEVICE_NOT_FOUND} when appropriate.
214      */
215     public final static int ERROR_FILE_ERROR = 1001;
216
217     /**
218      * Value of {@link #COLUMN_REASON} when an HTTP code was received that download manager
219      * can't handle.
220      */
221     public final static int ERROR_UNHANDLED_HTTP_CODE = 1002;
222
223     /**
224      * Value of {@link #COLUMN_REASON} when an error receiving or processing data occurred at
225      * the HTTP level.
226      */
227     public final static int ERROR_HTTP_DATA_ERROR = 1004;
228
229     /**
230      * Value of {@link #COLUMN_REASON} when there were too many redirects.
231      */
232     public final static int ERROR_TOO_MANY_REDIRECTS = 1005;
233
234     /**
235      * Value of {@link #COLUMN_REASON} when there was insufficient storage space. Typically,
236      * this is because the SD card is full.
237      */
238     public final static int ERROR_INSUFFICIENT_SPACE = 1006;
239
240     /**
241      * Value of {@link #COLUMN_REASON} when no external storage device was found. Typically,
242      * this is because the SD card is not mounted.
243      */
244     public final static int ERROR_DEVICE_NOT_FOUND = 1007;
245
246     /**
247      * Value of {@link #COLUMN_REASON} when some possibly transient error occurred but we can't
248      * resume the download.
249      */
250     public final static int ERROR_CANNOT_RESUME = 1008;
251
252     /**
253      * Value of {@link #COLUMN_REASON} when the requested destination file already exists (the
254      * download manager will not overwrite an existing file).
255      */
256     public final static int ERROR_FILE_ALREADY_EXISTS = 1009;
257
258     /**
259      * Value of {@link #COLUMN_REASON} when the download has failed because of
260      * {@link NetworkPolicyManager} controls on the requesting application.
261      *
262      * @hide
263      */
264     public final static int ERROR_BLOCKED = 1010;
265
266     /**
267      * Value of {@link #COLUMN_REASON} when the download is paused because some network error
268      * occurred and the download manager is waiting before retrying the request.
269      */
270     public final static int PAUSED_WAITING_TO_RETRY = 1;
271
272     /**
273      * Value of {@link #COLUMN_REASON} when the download is waiting for network connectivity to
274      * proceed.
275      */
276     public final static int PAUSED_WAITING_FOR_NETWORK = 2;
277
278     /**
279      * Value of {@link #COLUMN_REASON} when the download exceeds a size limit for downloads over
280      * the mobile network and the download manager is waiting for a Wi-Fi connection to proceed.
281      */
282     public final static int PAUSED_QUEUED_FOR_WIFI = 3;
283
284     /**
285      * Value of {@link #COLUMN_REASON} when the download is paused for some other reason.
286      */
287     public final static int PAUSED_UNKNOWN = 4;
288
289    /**
290     * Value of {@link #COLUMN_REASON} when the download is paused manually.
291     *
292     * @hide
293     */
294     public final static int PAUSED_MANUAL = 5;
295
296     /**
297      * Broadcast intent action sent by the download manager when a download completes.
298      */
299     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
300     public final static String ACTION_DOWNLOAD_COMPLETE = "android.intent.action.DOWNLOAD_COMPLETE";
301
302     /**
303      * Broadcast intent action sent by the download manager when the user clicks on a running
304      * download, either from a system notification or from the downloads UI.
305      */
306     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
307     public final static String ACTION_NOTIFICATION_CLICKED =
308             "android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED";
309
310     /**
311      * Intent action to launch an activity to display all downloads.
312      */
313     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
314     public final static String ACTION_VIEW_DOWNLOADS = "android.intent.action.VIEW_DOWNLOADS";
315
316     /**
317      * Intent extra included with {@link #ACTION_VIEW_DOWNLOADS} to start DownloadApp in
318      * sort-by-size mode.
319      */
320     public final static String INTENT_EXTRAS_SORT_BY_SIZE =
321             "android.app.DownloadManager.extra_sortBySize";
322
323     /**
324      * Intent extra included with {@link #ACTION_DOWNLOAD_COMPLETE} intents, indicating the ID (as a
325      * long) of the download that just completed.
326      */
327     public static final String EXTRA_DOWNLOAD_ID = "extra_download_id";
328
329     /**
330      * When clicks on multiple notifications are received, the following
331      * provides an array of download ids corresponding to the download notification that was
332      * clicked. It can be retrieved by the receiver of this
333      * Intent using {@link android.content.Intent#getLongArrayExtra(String)}.
334      */
335     public static final String EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS = "extra_click_download_ids";
336
337     /**
338      * columns to request from DownloadProvider.
339      * @hide
340      */
341     public static final String[] UNDERLYING_COLUMNS = new String[] {
342         DownloadManager.COLUMN_ID,
343         DownloadManager.COLUMN_LOCAL_FILENAME,
344         DownloadManager.COLUMN_MEDIAPROVIDER_URI,
345         DownloadManager.COLUMN_DESTINATION,
346         DownloadManager.COLUMN_TITLE,
347         DownloadManager.COLUMN_DESCRIPTION,
348         DownloadManager.COLUMN_URI,
349         DownloadManager.COLUMN_STATUS,
350         DownloadManager.COLUMN_FILE_NAME_HINT,
351         DownloadManager.COLUMN_MEDIA_TYPE,
352         DownloadManager.COLUMN_TOTAL_SIZE_BYTES,
353         DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP,
354         DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR,
355         DownloadManager.COLUMN_ALLOW_WRITE,
356         DownloadManager.COLUMN_LOCAL_URI,
357         DownloadManager.COLUMN_REASON
358     };
359
360     /**
361      * This class contains all the information necessary to request a new download. The URI is the
362      * only required parameter.
363      *
364      * Note that the default download destination is a shared volume where the system might delete
365      * your file if it needs to reclaim space for system use. If this is a problem, use a location
366      * on external storage (see {@link #setDestinationUri(Uri)}.
367      */
368     public static class Request {
369         /**
370          * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
371          * {@link ConnectivityManager#TYPE_MOBILE}.
372          */
373         public static final int NETWORK_MOBILE = 1 << 0;
374
375         /**
376          * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
377          * {@link ConnectivityManager#TYPE_WIFI}.
378          */
379         public static final int NETWORK_WIFI = 1 << 1;
380
381         /**
382          * Bit flag for {@link #setAllowedNetworkTypes} corresponding to
383          * {@link ConnectivityManager#TYPE_BLUETOOTH}.
384          * @hide
385          */
386         @Deprecated
387         public static final int NETWORK_BLUETOOTH = 1 << 2;
388
389         private Uri mUri;
390         private Uri mDestinationUri;
391         private List<Pair<String, String>> mRequestHeaders = new ArrayList<Pair<String, String>>();
392         private CharSequence mTitle;
393         private CharSequence mDescription;
394         private String mMimeType;
395         private int mAllowedNetworkTypes = ~0; // default to all network types allowed
396         private boolean mRoamingAllowed = true;
397         private boolean mMeteredAllowed = true;
398         private int mFlags = 0;
399         private boolean mIsVisibleInDownloadsUi = true;
400         private boolean mScannable = false;
401         private boolean mUseSystemCache = false;
402         /** if a file is designated as a MediaScanner scannable file, the following value is
403          * stored in the database column {@link Downloads.Impl#COLUMN_MEDIA_SCANNED}.
404          */
405         private static final int SCANNABLE_VALUE_YES = 0;
406         // value of 1 is stored in the above column by DownloadProvider after it is scanned by
407         // MediaScanner
408         /** if a file is designated as a file that should not be scanned by MediaScanner,
409          * the following value is stored in the database column
410          * {@link Downloads.Impl#COLUMN_MEDIA_SCANNED}.
411          */
412         private static final int SCANNABLE_VALUE_NO = 2;
413
414         /**
415          * This download is visible but only shows in the notifications
416          * while it's in progress.
417          */
418         public static final int VISIBILITY_VISIBLE = 0;
419
420         /**
421          * This download is visible and shows in the notifications while
422          * in progress and after completion.
423          */
424         public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED = 1;
425
426         /**
427          * This download doesn't show in the UI or in the notifications.
428          */
429         public static final int VISIBILITY_HIDDEN = 2;
430
431         /**
432          * This download shows in the notifications after completion ONLY.
433          * It is usuable only with
434          * {@link DownloadManager#addCompletedDownload(String, String,
435          * boolean, String, String, long, boolean)}.
436          */
437         public static final int VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION = 3;
438
439         /** can take any of the following values: {@link #VISIBILITY_HIDDEN}
440          * {@link #VISIBILITY_VISIBLE_NOTIFY_COMPLETED}, {@link #VISIBILITY_VISIBLE},
441          * {@link #VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION}
442          */
443         private int mNotificationVisibility = VISIBILITY_VISIBLE;
444
445         /**
446          * @param uri the HTTP or HTTPS URI to download.
447          */
448         public Request(Uri uri) {
449             if (uri == null) {
450                 throw new NullPointerException();
451             }
452             String scheme = uri.getScheme();
453             if (scheme == null || (!scheme.equals("http") && !scheme.equals("https"))) {
454                 throw new IllegalArgumentException("Can only download HTTP/HTTPS URIs: " + uri);
455             }
456             mUri = uri;
457         }
458
459         Request(String uriString) {
460             mUri = Uri.parse(uriString);
461         }
462
463         /**
464          * Set the local destination for the downloaded file. Must be a file URI to a path on
465          * external storage, and the calling application must have the WRITE_EXTERNAL_STORAGE
466          * permission.
467          * <p>
468          * The downloaded file is not scanned by MediaScanner.
469          * But it can be made scannable by calling {@link #allowScanningByMediaScanner()}.
470          * <p>
471          * By default, downloads are saved to a generated filename in the shared download cache and
472          * may be deleted by the system at any time to reclaim space.
473          *
474          * @return this object
475          */
476         public Request setDestinationUri(Uri uri) {
477             mDestinationUri = uri;
478             return this;
479         }
480
481         /**
482          * Set the local destination for the downloaded file to the system cache dir (/cache).
483          * This is only available to System apps with the permission
484          * {@link android.Manifest.permission#ACCESS_CACHE_FILESYSTEM}.
485          * <p>
486          * The downloaded file is not scanned by MediaScanner.
487          * But it can be made scannable by calling {@link #allowScanningByMediaScanner()}.
488          * <p>
489          * Files downloaded to /cache may be deleted by the system at any time to reclaim space.
490          *
491          * @return this object
492          * @hide
493          */
494         public Request setDestinationToSystemCache() {
495             mUseSystemCache = true;
496             return this;
497         }
498
499         /**
500          * Set the local destination for the downloaded file to a path within
501          * the application's external files directory (as returned by
502          * {@link Context#getExternalFilesDir(String)}.
503          * <p>
504          * The downloaded file is not scanned by MediaScanner. But it can be
505          * made scannable by calling {@link #allowScanningByMediaScanner()}.
506          *
507          * @param context the {@link Context} to use in determining the external
508          *            files directory
509          * @param dirType the directory type to pass to
510          *            {@link Context#getExternalFilesDir(String)}
511          * @param subPath the path within the external directory, including the
512          *            destination filename
513          * @return this object
514          * @throws IllegalStateException If the external storage directory
515          *             cannot be found or created.
516          */
517         public Request setDestinationInExternalFilesDir(Context context, String dirType,
518                 String subPath) {
519             final File file = context.getExternalFilesDir(dirType);
520             if (file == null) {
521                 throw new IllegalStateException("Failed to get external storage files directory");
522             } else if (file.exists()) {
523                 if (!file.isDirectory()) {
524                     throw new IllegalStateException(file.getAbsolutePath() +
525                             " already exists and is not a directory");
526                 }
527             } else {
528                 if (!file.mkdirs()) {
529                     throw new IllegalStateException("Unable to create directory: "+
530                             file.getAbsolutePath());
531                 }
532             }
533             setDestinationFromBase(file, subPath);
534             return this;
535         }
536
537         /**
538          * Set the local destination for the downloaded file to a path within
539          * the public external storage directory (as returned by
540          * {@link Environment#getExternalStoragePublicDirectory(String)}).
541          * <p>
542          * The downloaded file is not scanned by MediaScanner. But it can be
543          * made scannable by calling {@link #allowScanningByMediaScanner()}.
544          *
545          * @param dirType the directory type to pass to {@link Environment#getExternalStoragePublicDirectory(String)}
546          * @param subPath the path within the external directory, including the
547          *            destination filename
548          * @return this object
549          * @throws IllegalStateException If the external storage directory
550          *             cannot be found or created.
551          */
552         public Request setDestinationInExternalPublicDir(String dirType, String subPath) {
553             File file = Environment.getExternalStoragePublicDirectory(dirType);
554             if (file == null) {
555                 throw new IllegalStateException("Failed to get external storage public directory");
556             } else if (file.exists()) {
557                 if (!file.isDirectory()) {
558                     throw new IllegalStateException(file.getAbsolutePath() +
559                             " already exists and is not a directory");
560                 }
561             } else {
562                 if (!file.mkdirs()) {
563                     throw new IllegalStateException("Unable to create directory: "+
564                             file.getAbsolutePath());
565                 }
566             }
567             setDestinationFromBase(file, subPath);
568             return this;
569         }
570
571         private void setDestinationFromBase(File base, String subPath) {
572             if (subPath == null) {
573                 throw new NullPointerException("subPath cannot be null");
574             }
575             mDestinationUri = Uri.withAppendedPath(Uri.fromFile(base), subPath);
576         }
577
578         /**
579          * If the file to be downloaded is to be scanned by MediaScanner, this method
580          * should be called before {@link DownloadManager#enqueue(Request)} is called.
581          */
582         public void allowScanningByMediaScanner() {
583             mScannable = true;
584         }
585
586         /**
587          * Add an HTTP header to be included with the download request.  The header will be added to
588          * the end of the list.
589          * @param header HTTP header name
590          * @param value header value
591          * @return this object
592          * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2">HTTP/1.1
593          *      Message Headers</a>
594          */
595         public Request addRequestHeader(String header, String value) {
596             if (header == null) {
597                 throw new NullPointerException("header cannot be null");
598             }
599             if (header.contains(":")) {
600                 throw new IllegalArgumentException("header may not contain ':'");
601             }
602             if (value == null) {
603                 value = "";
604             }
605             mRequestHeaders.add(Pair.create(header, value));
606             return this;
607         }
608
609         /**
610          * Set the title of this download, to be displayed in notifications (if enabled).  If no
611          * title is given, a default one will be assigned based on the download filename, once the
612          * download starts.
613          * @return this object
614          */
615         public Request setTitle(CharSequence title) {
616             mTitle = title;
617             return this;
618         }
619
620         /**
621          * Set a description of this download, to be displayed in notifications (if enabled)
622          * @return this object
623          */
624         public Request setDescription(CharSequence description) {
625             mDescription = description;
626             return this;
627         }
628
629         /**
630          * Set the MIME content type of this download.  This will override the content type declared
631          * in the server's response.
632          * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7">HTTP/1.1
633          *      Media Types</a>
634          * @return this object
635          */
636         public Request setMimeType(String mimeType) {
637             mMimeType = mimeType;
638             return this;
639         }
640
641         /**
642          * Control whether a system notification is posted by the download manager while this
643          * download is running. If enabled, the download manager posts notifications about downloads
644          * through the system {@link android.app.NotificationManager}. By default, a notification is
645          * shown.
646          *
647          * If set to false, this requires the permission
648          * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
649          *
650          * @param show whether the download manager should show a notification for this download.
651          * @return this object
652          * @deprecated use {@link #setNotificationVisibility(int)}
653          */
654         @Deprecated
655         public Request setShowRunningNotification(boolean show) {
656             return (show) ? setNotificationVisibility(VISIBILITY_VISIBLE) :
657                     setNotificationVisibility(VISIBILITY_HIDDEN);
658         }
659
660         /**
661          * Control whether a system notification is posted by the download manager while this
662          * download is running or when it is completed.
663          * If enabled, the download manager posts notifications about downloads
664          * through the system {@link android.app.NotificationManager}.
665          * By default, a notification is shown only when the download is in progress.
666          *<p>
667          * It can take the following values: {@link #VISIBILITY_HIDDEN},
668          * {@link #VISIBILITY_VISIBLE},
669          * {@link #VISIBILITY_VISIBLE_NOTIFY_COMPLETED}.
670          *<p>
671          * If set to {@link #VISIBILITY_HIDDEN}, this requires the permission
672          * android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.
673          *
674          * @param visibility the visibility setting value
675          * @return this object
676          */
677         public Request setNotificationVisibility(int visibility) {
678             mNotificationVisibility = visibility;
679             return this;
680         }
681
682         /**
683          * Restrict the types of networks over which this download may proceed.
684          * By default, all network types are allowed. Consider using
685          * {@link #setAllowedOverMetered(boolean)} instead, since it's more
686          * flexible.
687          * <p>
688          * As of {@link android.os.Build.VERSION_CODES#N}, setting only the
689          * {@link #NETWORK_WIFI} flag here is equivalent to calling
690          * {@link #setAllowedOverMetered(boolean)} with {@code false}.
691          *
692          * @param flags any combination of the NETWORK_* bit flags.
693          * @return this object
694          */
695         public Request setAllowedNetworkTypes(int flags) {
696             mAllowedNetworkTypes = flags;
697             return this;
698         }
699
700         /**
701          * Set whether this download may proceed over a roaming connection.  By default, roaming is
702          * allowed.
703          * @param allowed whether to allow a roaming connection to be used
704          * @return this object
705          */
706         public Request setAllowedOverRoaming(boolean allowed) {
707             mRoamingAllowed = allowed;
708             return this;
709         }
710
711         /**
712          * Set whether this download may proceed over a metered network
713          * connection. By default, metered networks are allowed.
714          *
715          * @see ConnectivityManager#isActiveNetworkMetered()
716          */
717         public Request setAllowedOverMetered(boolean allow) {
718             mMeteredAllowed = allow;
719             return this;
720         }
721
722         /**
723          * Specify that to run this download, the device needs to be plugged in.
724          * This defaults to false.
725          *
726          * @param requiresCharging Whether or not the device is plugged in.
727          * @see android.app.job.JobInfo.Builder#setRequiresCharging(boolean)
728          */
729         public Request setRequiresCharging(boolean requiresCharging) {
730             if (requiresCharging) {
731                 mFlags |= Downloads.Impl.FLAG_REQUIRES_CHARGING;
732             } else {
733                 mFlags &= ~Downloads.Impl.FLAG_REQUIRES_CHARGING;
734             }
735             return this;
736         }
737
738         /**
739          * Specify that to run, the download needs the device to be in idle
740          * mode. This defaults to false.
741          * <p>
742          * Idle mode is a loose definition provided by the system, which means
743          * that the device is not in use, and has not been in use for some time.
744          *
745          * @param requiresDeviceIdle Whether or not the device need be within an
746          *            idle maintenance window.
747          * @see android.app.job.JobInfo.Builder#setRequiresDeviceIdle(boolean)
748          */
749         public Request setRequiresDeviceIdle(boolean requiresDeviceIdle) {
750             if (requiresDeviceIdle) {
751                 mFlags |= Downloads.Impl.FLAG_REQUIRES_DEVICE_IDLE;
752             } else {
753                 mFlags &= ~Downloads.Impl.FLAG_REQUIRES_DEVICE_IDLE;
754             }
755             return this;
756         }
757
758         /**
759          * Set whether this download should be displayed in the system's Downloads UI. True by
760          * default.
761          * @param isVisible whether to display this download in the Downloads UI
762          * @return this object
763          */
764         public Request setVisibleInDownloadsUi(boolean isVisible) {
765             mIsVisibleInDownloadsUi = isVisible;
766             return this;
767         }
768
769         /**
770          * @return ContentValues to be passed to DownloadProvider.insert()
771          */
772         ContentValues toContentValues(String packageName) {
773             ContentValues values = new ContentValues();
774             assert mUri != null;
775             values.put(Downloads.Impl.COLUMN_URI, mUri.toString());
776             values.put(Downloads.Impl.COLUMN_IS_PUBLIC_API, true);
777             values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE, packageName);
778
779             if (mDestinationUri != null) {
780                 values.put(Downloads.Impl.COLUMN_DESTINATION, Downloads.Impl.DESTINATION_FILE_URI);
781                 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, mDestinationUri.toString());
782             } else {
783                 values.put(Downloads.Impl.COLUMN_DESTINATION,
784                            (this.mUseSystemCache) ?
785                                    Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION :
786                                    Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE);
787             }
788             // is the file supposed to be media-scannable?
789             values.put(Downloads.Impl.COLUMN_MEDIA_SCANNED, (mScannable) ? SCANNABLE_VALUE_YES :
790                     SCANNABLE_VALUE_NO);
791
792             if (!mRequestHeaders.isEmpty()) {
793                 encodeHttpHeaders(values);
794             }
795
796             putIfNonNull(values, Downloads.Impl.COLUMN_TITLE, mTitle);
797             putIfNonNull(values, Downloads.Impl.COLUMN_DESCRIPTION, mDescription);
798             putIfNonNull(values, Downloads.Impl.COLUMN_MIME_TYPE, mMimeType);
799
800             values.put(Downloads.Impl.COLUMN_VISIBILITY, mNotificationVisibility);
801             values.put(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES, mAllowedNetworkTypes);
802             values.put(Downloads.Impl.COLUMN_ALLOW_ROAMING, mRoamingAllowed);
803             values.put(Downloads.Impl.COLUMN_ALLOW_METERED, mMeteredAllowed);
804             values.put(Downloads.Impl.COLUMN_FLAGS, mFlags);
805             values.put(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, mIsVisibleInDownloadsUi);
806
807             return values;
808         }
809
810         private void encodeHttpHeaders(ContentValues values) {
811             int index = 0;
812             for (Pair<String, String> header : mRequestHeaders) {
813                 String headerString = header.first + ": " + header.second;
814                 values.put(Downloads.Impl.RequestHeaders.INSERT_KEY_PREFIX + index, headerString);
815                 index++;
816             }
817         }
818
819         private void putIfNonNull(ContentValues contentValues, String key, Object value) {
820             if (value != null) {
821                 contentValues.put(key, value.toString());
822             }
823         }
824     }
825
826     /**
827      * This class may be used to filter download manager queries.
828      */
829     public static class Query {
830         /**
831          * Constant for use with {@link #orderBy}
832          * @hide
833          */
834         public static final int ORDER_ASCENDING = 1;
835
836         /**
837          * Constant for use with {@link #orderBy}
838          * @hide
839          */
840         public static final int ORDER_DESCENDING = 2;
841
842         private long[] mIds = null;
843         private Integer mStatusFlags = null;
844         private String mFilterString = null;
845         private String mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
846         private int mOrderDirection = ORDER_DESCENDING;
847         private boolean mOnlyIncludeVisibleInDownloadsUi = false;
848
849         /**
850          * Include only the downloads with the given IDs.
851          * @return this object
852          */
853         public Query setFilterById(long... ids) {
854             mIds = ids;
855             return this;
856         }
857
858         /**
859          *
860          * Include only the downloads that contains the given string in its name.
861          * @return this object
862          * @hide
863          */
864         public Query setFilterByString(@Nullable String filter) {
865             mFilterString = filter;
866             return this;
867         }
868
869         /**
870          * Include only downloads with status matching any the given status flags.
871          * @param flags any combination of the STATUS_* bit flags
872          * @return this object
873          */
874         public Query setFilterByStatus(int flags) {
875             mStatusFlags = flags;
876             return this;
877         }
878
879         /**
880          * Controls whether this query includes downloads not visible in the system's Downloads UI.
881          * @param value if true, this query will only include downloads that should be displayed in
882          *            the system's Downloads UI; if false (the default), this query will include
883          *            both visible and invisible downloads.
884          * @return this object
885          * @hide
886          */
887         public Query setOnlyIncludeVisibleInDownloadsUi(boolean value) {
888             mOnlyIncludeVisibleInDownloadsUi = value;
889             return this;
890         }
891
892         /**
893          * Change the sort order of the returned Cursor.
894          *
895          * @param column one of the COLUMN_* constants; currently, only
896          *         {@link #COLUMN_LAST_MODIFIED_TIMESTAMP} and {@link #COLUMN_TOTAL_SIZE_BYTES} are
897          *         supported.
898          * @param direction either {@link #ORDER_ASCENDING} or {@link #ORDER_DESCENDING}
899          * @return this object
900          * @hide
901          */
902         public Query orderBy(String column, int direction) {
903             if (direction != ORDER_ASCENDING && direction != ORDER_DESCENDING) {
904                 throw new IllegalArgumentException("Invalid direction: " + direction);
905             }
906
907             if (column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP)) {
908                 mOrderByColumn = Downloads.Impl.COLUMN_LAST_MODIFICATION;
909             } else if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) {
910                 mOrderByColumn = Downloads.Impl.COLUMN_TOTAL_BYTES;
911             } else {
912                 throw new IllegalArgumentException("Cannot order by " + column);
913             }
914             mOrderDirection = direction;
915             return this;
916         }
917
918         /**
919          * Run this query using the given ContentResolver.
920          * @param projection the projection to pass to ContentResolver.query()
921          * @return the Cursor returned by ContentResolver.query()
922          */
923         Cursor runQuery(ContentResolver resolver, String[] projection, Uri baseUri) {
924             Uri uri = baseUri;
925             List<String> selectionParts = new ArrayList<String>();
926             String[] selectionArgs = null;
927
928             int whereArgsCount = (mIds == null) ? 0 : mIds.length;
929             whereArgsCount = (mFilterString == null) ? whereArgsCount : whereArgsCount + 1;
930             selectionArgs = new String[whereArgsCount];
931
932             if (whereArgsCount > 0) {
933                 if (mIds != null) {
934                     selectionParts.add(getWhereClauseForIds(mIds));
935                     getWhereArgsForIds(mIds, selectionArgs);
936                 }
937
938                 if (mFilterString != null) {
939                     selectionParts.add(Downloads.Impl.COLUMN_TITLE + " LIKE ?");
940                     selectionArgs[selectionArgs.length - 1] = "%" + mFilterString + "%";
941                 }
942             }
943
944             if (mStatusFlags != null) {
945                 List<String> parts = new ArrayList<String>();
946                 if ((mStatusFlags & STATUS_PENDING) != 0) {
947                     parts.add(statusClause("=", Downloads.Impl.STATUS_PENDING));
948                 }
949                 if ((mStatusFlags & STATUS_RUNNING) != 0) {
950                     parts.add(statusClause("=", Downloads.Impl.STATUS_RUNNING));
951                 }
952                 if ((mStatusFlags & STATUS_PAUSED) != 0) {
953                     parts.add(statusClause("=", Downloads.Impl.STATUS_PAUSED_BY_APP));
954                     parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_TO_RETRY));
955                     parts.add(statusClause("=", Downloads.Impl.STATUS_WAITING_FOR_NETWORK));
956                     parts.add(statusClause("=", Downloads.Impl.STATUS_QUEUED_FOR_WIFI));
957                     parts.add(statusClause("=", Downloads.Impl.STATUS_PAUSED_MANUAL));
958                 }
959                 if ((mStatusFlags & STATUS_SUCCESSFUL) != 0) {
960                     parts.add(statusClause("=", Downloads.Impl.STATUS_SUCCESS));
961                 }
962                 if ((mStatusFlags & STATUS_FAILED) != 0) {
963                     parts.add("(" + statusClause(">=", 400)
964                               + " AND " + statusClause("<", 600) + ")");
965                 }
966                 selectionParts.add(joinStrings(" OR ", parts));
967             }
968
969             if (mOnlyIncludeVisibleInDownloadsUi) {
970                 selectionParts.add(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI + " != '0'");
971             }
972
973             // only return rows which are not marked 'deleted = 1'
974             selectionParts.add(Downloads.Impl.COLUMN_DELETED + " != '1'");
975
976             String selection = joinStrings(" AND ", selectionParts);
977             String orderDirection = (mOrderDirection == ORDER_ASCENDING ? "ASC" : "DESC");
978             String orderBy = mOrderByColumn + " " + orderDirection;
979
980             return resolver.query(uri, projection, selection, selectionArgs, orderBy);
981         }
982
983         private String joinStrings(String joiner, Iterable<String> parts) {
984             StringBuilder builder = new StringBuilder();
985             boolean first = true;
986             for (String part : parts) {
987                 if (!first) {
988                     builder.append(joiner);
989                 }
990                 builder.append(part);
991                 first = false;
992             }
993             return builder.toString();
994         }
995
996         private String statusClause(String operator, int value) {
997             return Downloads.Impl.COLUMN_STATUS + operator + "'" + value + "'";
998         }
999     }
1000
1001     private final ContentResolver mResolver;
1002     private final String mPackageName;
1003
1004     private Uri mBaseUri = Downloads.Impl.CONTENT_URI;
1005     private boolean mAccessFilename;
1006
1007     /**
1008      * @hide
1009      */
1010     public DownloadManager(Context context) {
1011         mResolver = context.getContentResolver();
1012         mPackageName = context.getPackageName();
1013
1014         // Callers can access filename columns when targeting old platform
1015         // versions; otherwise we throw telling them it's deprecated.
1016         mAccessFilename = context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N;
1017     }
1018
1019     /**
1020      * Makes this object access the download provider through /all_downloads URIs rather than
1021      * /my_downloads URIs, for clients that have permission to do so.
1022      * @hide
1023      */
1024     public void setAccessAllDownloads(boolean accessAllDownloads) {
1025         if (accessAllDownloads) {
1026             mBaseUri = Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI;
1027         } else {
1028             mBaseUri = Downloads.Impl.CONTENT_URI;
1029         }
1030     }
1031
1032     /** {@hide} */
1033     public void setAccessFilename(boolean accessFilename) {
1034         mAccessFilename = accessFilename;
1035     }
1036
1037     /**
1038      * Enqueue a new download.  The download will start automatically once the download manager is
1039      * ready to execute it and connectivity is available.
1040      *
1041      * @param request the parameters specifying this download
1042      * @return an ID for the download, unique across the system.  This ID is used to make future
1043      * calls related to this download.
1044      */
1045     public long enqueue(Request request) {
1046         ContentValues values = request.toContentValues(mPackageName);
1047         Uri downloadUri = mResolver.insert(Downloads.Impl.CONTENT_URI, values);
1048         long id = Long.parseLong(downloadUri.getLastPathSegment());
1049         return id;
1050     }
1051
1052     /**
1053      * Marks the specified download as 'to be deleted'. This is done when a completed download
1054      * is to be removed but the row was stored without enough info to delete the corresponding
1055      * metadata from Mediaprovider database. Actual cleanup of this row is done in DownloadService.
1056      *
1057      * @param ids the IDs of the downloads to be marked 'deleted'
1058      * @return the number of downloads actually updated
1059      * @hide
1060      */
1061     public int markRowDeleted(long... ids) {
1062         if (ids == null || ids.length == 0) {
1063             // called with nothing to remove!
1064             throw new IllegalArgumentException("input param 'ids' can't be null");
1065         }
1066         return mResolver.delete(mBaseUri, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
1067     }
1068
1069     /**
1070      * Cancel downloads and remove them from the download manager.  Each download will be stopped if
1071      * it was running, and it will no longer be accessible through the download manager.
1072      * If there is a downloaded file, partial or complete, it is deleted.
1073      *
1074      * @param ids the IDs of the downloads to remove
1075      * @return the number of downloads actually removed
1076      */
1077     public int remove(long... ids) {
1078         return markRowDeleted(ids);
1079     }
1080
1081     /**
1082      * Query the download manager about downloads that have been requested.
1083      * @param query parameters specifying filters for this query
1084      * @return a Cursor over the result set of downloads, with columns consisting of all the
1085      * COLUMN_* constants.
1086      */
1087     public Cursor query(Query query) {
1088         Cursor underlyingCursor = query.runQuery(mResolver, UNDERLYING_COLUMNS, mBaseUri);
1089         if (underlyingCursor == null) {
1090             return null;
1091         }
1092         return new CursorTranslator(underlyingCursor, mBaseUri, mAccessFilename);
1093     }
1094
1095     /**
1096      * Open a downloaded file for reading.  The download must have completed.
1097      * @param id the ID of the download
1098      * @return a read-only {@link ParcelFileDescriptor}
1099      * @throws FileNotFoundException if the destination file does not already exist
1100      */
1101     public ParcelFileDescriptor openDownloadedFile(long id) throws FileNotFoundException {
1102         return mResolver.openFileDescriptor(getDownloadUri(id), "r");
1103     }
1104
1105     /**
1106      * Returns the {@link Uri} of the given downloaded file id, if the file is
1107      * downloaded successfully. Otherwise, null is returned.
1108      *
1109      * @param id the id of the downloaded file.
1110      * @return the {@link Uri} of the given downloaded file id, if download was
1111      *         successful. null otherwise.
1112      */
1113     public Uri getUriForDownloadedFile(long id) {
1114         // to check if the file is in cache, get its destination from the database
1115         Query query = new Query().setFilterById(id);
1116         Cursor cursor = null;
1117         try {
1118             cursor = query(query);
1119             if (cursor == null) {
1120                 return null;
1121             }
1122             if (cursor.moveToFirst()) {
1123                 int status = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_STATUS));
1124                 if (DownloadManager.STATUS_SUCCESSFUL == status) {
1125                     return ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, id);
1126                 }
1127             }
1128         } finally {
1129             if (cursor != null) {
1130                 cursor.close();
1131             }
1132         }
1133         // downloaded file not found or its status is not 'successfully completed'
1134         return null;
1135     }
1136
1137     /**
1138      * Returns the media type of the given downloaded file id, if the file was
1139      * downloaded successfully. Otherwise, null is returned.
1140      *
1141      * @param id the id of the downloaded file.
1142      * @return the media type of the given downloaded file id, if download was successful. null
1143      * otherwise.
1144      */
1145     public String getMimeTypeForDownloadedFile(long id) {
1146         Query query = new Query().setFilterById(id);
1147         Cursor cursor = null;
1148         try {
1149             cursor = query(query);
1150             if (cursor == null) {
1151                 return null;
1152             }
1153             while (cursor.moveToFirst()) {
1154                 return cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_MEDIA_TYPE));
1155             }
1156         } finally {
1157             if (cursor != null) {
1158                 cursor.close();
1159             }
1160         }
1161         // downloaded file not found or its status is not 'successfully completed'
1162         return null;
1163     }
1164
1165     /**
1166      * Restart the given downloads, which must have already completed (successfully or not).  This
1167      * method will only work when called from within the download manager's process.
1168      * @param ids the IDs of the downloads
1169      * @hide
1170      */
1171     public void restartDownload(long... ids) {
1172         Cursor cursor = query(new Query().setFilterById(ids));
1173         try {
1174             for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
1175                 int status = cursor.getInt(cursor.getColumnIndex(COLUMN_STATUS));
1176                 if (status != STATUS_SUCCESSFUL && status != STATUS_FAILED) {
1177                     throw new IllegalArgumentException("Cannot restart incomplete download: "
1178                             + cursor.getLong(cursor.getColumnIndex(COLUMN_ID)));
1179                 }
1180             }
1181         } finally {
1182             cursor.close();
1183         }
1184
1185         ContentValues values = new ContentValues();
1186         values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, 0);
1187         values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, -1);
1188         values.putNull(Downloads.Impl._DATA);
1189         values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING);
1190         values.put(Downloads.Impl.COLUMN_FAILED_CONNECTIONS, 0);
1191         mResolver.update(mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
1192     }
1193
1194     /**
1195      * Force the given downloads to proceed even if their size is larger than
1196      * {@link #getMaxBytesOverMobile(Context)}.
1197      *
1198      * @hide
1199      */
1200     public void forceDownload(long... ids) {
1201         ContentValues values = new ContentValues();
1202         values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING);
1203         values.put(Downloads.Impl.COLUMN_CONTROL, Downloads.Impl.CONTROL_RUN);
1204         values.put(Downloads.Impl.COLUMN_BYPASS_RECOMMENDED_SIZE_LIMIT, 1);
1205         mResolver.update(mBaseUri, values, getWhereClauseForIds(ids), getWhereArgsForIds(ids));
1206     }
1207
1208     /**
1209      * Pause the given running download manually.
1210      *
1211      * @param id the ID of the download to be paused
1212      * @return the number of downloads actually updated
1213      * @hide
1214      */
1215     public int pauseDownload(long id) {
1216         ContentValues values = new ContentValues();
1217         values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PAUSED_MANUAL);
1218
1219         return mResolver.update(ContentUris.withAppendedId(mBaseUri, id), values, null, null);
1220     }
1221
1222     /**
1223      * Resume the given paused download manually.
1224      *
1225      * @param id the ID of the download to be resumed
1226      * @return the number of downloads actually updated
1227      * @hide
1228      */
1229     public int resumeDownload(long id) {
1230        ContentValues values = new ContentValues();
1231        values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_RUNNING);
1232
1233        return mResolver.update(ContentUris.withAppendedId(mBaseUri, id), values, null, null);
1234     }
1235
1236     /**
1237      * Returns maximum size, in bytes, of downloads that may go over a mobile connection; or null if
1238      * there's no limit
1239      *
1240      * @param context the {@link Context} to use for accessing the {@link ContentResolver}
1241      * @return maximum size, in bytes, of downloads that may go over a mobile connection; or null if
1242      * there's no limit
1243      */
1244     public static Long getMaxBytesOverMobile(Context context) {
1245         try {
1246             return Settings.Global.getLong(context.getContentResolver(),
1247                     Settings.Global.DOWNLOAD_MAX_BYTES_OVER_MOBILE);
1248         } catch (SettingNotFoundException exc) {
1249             return null;
1250         }
1251     }
1252
1253     /**
1254      * Rename the given download if the download has completed
1255      *
1256      * @param context the {@link Context} to use in case need to update MediaProvider
1257      * @param id the downloaded id
1258      * @param displayName the new name to rename to
1259      * @return true if rename was successful, false otherwise
1260      * @hide
1261      */
1262     public boolean rename(Context context, long id, String displayName) {
1263         if (!FileUtils.isValidFatFilename(displayName)) {
1264             throw new SecurityException(displayName + " is not a valid filename");
1265         }
1266
1267         Query query = new Query().setFilterById(id);
1268         Cursor cursor = null;
1269         String oldDisplayName = null;
1270         String mimeType = null;
1271         try {
1272             cursor = query(query);
1273             if (cursor == null) {
1274                 return false;
1275             }
1276             if (cursor.moveToFirst()) {
1277                 int status = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_STATUS));
1278                 if (DownloadManager.STATUS_SUCCESSFUL != status) {
1279                     return false;
1280                 }
1281                 oldDisplayName = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_TITLE));
1282                 mimeType = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_MEDIA_TYPE));
1283             }
1284         } finally {
1285             if (cursor != null) {
1286                 cursor.close();
1287             }
1288         }
1289
1290         if (oldDisplayName == null || mimeType == null) {
1291             throw new IllegalStateException(
1292                     "Document with id " + id + " does not exist");
1293         }
1294
1295         final File parent = Environment.getExternalStoragePublicDirectory(
1296                 Environment.DIRECTORY_DOWNLOADS);
1297
1298         final File before = new File(parent, oldDisplayName);
1299         final File after = new File(parent, displayName);
1300
1301         if (after.exists()) {
1302             throw new IllegalStateException("Already exists " + after);
1303         }
1304         if (!before.renameTo(after)) {
1305             throw new IllegalStateException("Failed to rename to " + after);
1306         }
1307
1308         // Update MediaProvider if necessary
1309         if (mimeType.startsWith("image/")) {
1310             context.getContentResolver().delete(Images.Media.EXTERNAL_CONTENT_URI,
1311                     Images.Media.DATA + "=?",
1312                     new String[] {
1313                             before.getAbsolutePath()
1314                     });
1315
1316             Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1317             intent.setData(Uri.fromFile(after));
1318             context.sendBroadcast(intent);
1319         }
1320
1321         ContentValues values = new ContentValues();
1322         values.put(Downloads.Impl.COLUMN_TITLE, displayName);
1323         values.put(Downloads.Impl._DATA, after.toString());
1324         values.putNull(Downloads.Impl.COLUMN_MEDIAPROVIDER_URI);
1325         long[] ids = {id};
1326
1327         return (mResolver.update(mBaseUri, values, getWhereClauseForIds(ids),
1328                 getWhereArgsForIds(ids)) == 1);
1329     }
1330
1331     /**
1332      * Returns recommended maximum size, in bytes, of downloads that may go over a mobile
1333      * connection; or null if there's no recommended limit.  The user will have the option to bypass
1334      * this limit.
1335      *
1336      * @param context the {@link Context} to use for accessing the {@link ContentResolver}
1337      * @return recommended maximum size, in bytes, of downloads that may go over a mobile
1338      * connection; or null if there's no recommended limit.
1339      */
1340     public static Long getRecommendedMaxBytesOverMobile(Context context) {
1341         try {
1342             return Settings.Global.getLong(context.getContentResolver(),
1343                     Settings.Global.DOWNLOAD_RECOMMENDED_MAX_BYTES_OVER_MOBILE);
1344         } catch (SettingNotFoundException exc) {
1345             return null;
1346         }
1347     }
1348
1349     /** {@hide} */
1350     public static boolean isActiveNetworkExpensive(Context context) {
1351         // TODO: connect to NetworkPolicyManager
1352         return false;
1353     }
1354
1355     /** {@hide} */
1356     public static long getActiveNetworkWarningBytes(Context context) {
1357         // TODO: connect to NetworkPolicyManager
1358         return -1;
1359     }
1360
1361     /**
1362      * Adds a file to the downloads database system, so it could appear in Downloads App
1363      * (and thus become eligible for management by the Downloads App).
1364      * <p>
1365      * It is helpful to make the file scannable by MediaScanner by setting the param
1366      * isMediaScannerScannable to true. It makes the file visible in media managing
1367      * applications such as Gallery App, which could be a useful purpose of using this API.
1368      *
1369      * @param title the title that would appear for this file in Downloads App.
1370      * @param description the description that would appear for this file in Downloads App.
1371      * @param isMediaScannerScannable true if the file is to be scanned by MediaScanner. Files
1372      * scanned by MediaScanner appear in the applications used to view media (for example,
1373      * Gallery app).
1374      * @param mimeType mimetype of the file.
1375      * @param path absolute pathname to the file. The file should be world-readable, so that it can
1376      * be managed by the Downloads App and any other app that is used to read it (for example,
1377      * Gallery app to display the file, if the file contents represent a video/image).
1378      * @param length length of the downloaded file
1379      * @param showNotification true if a notification is to be sent, false otherwise
1380      * @return  an ID for the download entry added to the downloads app, unique across the system
1381      * This ID is used to make future calls related to this download.
1382      */
1383     public long addCompletedDownload(String title, String description,
1384             boolean isMediaScannerScannable, String mimeType, String path, long length,
1385             boolean showNotification) {
1386         return addCompletedDownload(title, description, isMediaScannerScannable, mimeType, path,
1387                 length, showNotification, false, null, null);
1388     }
1389
1390     /**
1391      * Adds a file to the downloads database system, so it could appear in Downloads App
1392      * (and thus become eligible for management by the Downloads App).
1393      * <p>
1394      * It is helpful to make the file scannable by MediaScanner by setting the param
1395      * isMediaScannerScannable to true. It makes the file visible in media managing
1396      * applications such as Gallery App, which could be a useful purpose of using this API.
1397      *
1398      * @param title the title that would appear for this file in Downloads App.
1399      * @param description the description that would appear for this file in Downloads App.
1400      * @param isMediaScannerScannable true if the file is to be scanned by MediaScanner. Files
1401      * scanned by MediaScanner appear in the applications used to view media (for example,
1402      * Gallery app).
1403      * @param mimeType mimetype of the file.
1404      * @param path absolute pathname to the file. The file should be world-readable, so that it can
1405      * be managed by the Downloads App and any other app that is used to read it (for example,
1406      * Gallery app to display the file, if the file contents represent a video/image).
1407      * @param length length of the downloaded file
1408      * @param showNotification true if a notification is to be sent, false otherwise
1409      * @param uri the original HTTP URI of the download
1410      * @param referer the HTTP Referer for the download
1411      * @return  an ID for the download entry added to the downloads app, unique across the system
1412      * This ID is used to make future calls related to this download.
1413      */
1414     public long addCompletedDownload(String title, String description,
1415             boolean isMediaScannerScannable, String mimeType, String path, long length,
1416             boolean showNotification, Uri uri, Uri referer) {
1417         return addCompletedDownload(title, description, isMediaScannerScannable, mimeType, path,
1418                 length, showNotification, false, uri, referer);
1419     }
1420
1421     /** {@hide} */
1422     public long addCompletedDownload(String title, String description,
1423             boolean isMediaScannerScannable, String mimeType, String path, long length,
1424             boolean showNotification, boolean allowWrite) {
1425         return addCompletedDownload(title, description, isMediaScannerScannable, mimeType, path,
1426                 length, showNotification, allowWrite, null, null);
1427     }
1428
1429     /** {@hide} */
1430     public long addCompletedDownload(String title, String description,
1431             boolean isMediaScannerScannable, String mimeType, String path, long length,
1432             boolean showNotification, boolean allowWrite, Uri uri, Uri referer) {
1433         // make sure the input args are non-null/non-zero
1434         validateArgumentIsNonEmpty("title", title);
1435         validateArgumentIsNonEmpty("description", description);
1436         validateArgumentIsNonEmpty("path", path);
1437         validateArgumentIsNonEmpty("mimeType", mimeType);
1438         if (length < 0) {
1439             throw new IllegalArgumentException(" invalid value for param: totalBytes");
1440         }
1441
1442         // if there is already an entry with the given path name in downloads.db, return its id
1443         Request request;
1444         if (uri != null) {
1445             request = new Request(uri);
1446         } else {
1447             request = new Request(NON_DOWNLOADMANAGER_DOWNLOAD);
1448         }
1449         request.setTitle(title)
1450                 .setDescription(description)
1451                 .setMimeType(mimeType);
1452         if (referer != null) {
1453             request.addRequestHeader("Referer", referer.toString());
1454         }
1455         ContentValues values = request.toContentValues(null);
1456         values.put(Downloads.Impl.COLUMN_DESTINATION,
1457                 Downloads.Impl.DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD);
1458         values.put(Downloads.Impl._DATA, path);
1459         values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_SUCCESS);
1460         values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, length);
1461         values.put(Downloads.Impl.COLUMN_MEDIA_SCANNED,
1462                 (isMediaScannerScannable) ? Request.SCANNABLE_VALUE_YES :
1463                         Request.SCANNABLE_VALUE_NO);
1464         values.put(Downloads.Impl.COLUMN_VISIBILITY, (showNotification) ?
1465                 Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION : Request.VISIBILITY_HIDDEN);
1466         values.put(Downloads.Impl.COLUMN_ALLOW_WRITE, allowWrite ? 1 : 0);
1467         Uri downloadUri = mResolver.insert(Downloads.Impl.CONTENT_URI, values);
1468         if (downloadUri == null) {
1469             return -1;
1470         }
1471         return Long.parseLong(downloadUri.getLastPathSegment());
1472     }
1473
1474     private static final String NON_DOWNLOADMANAGER_DOWNLOAD =
1475             "non-dwnldmngr-download-dont-retry2download";
1476
1477     private static void validateArgumentIsNonEmpty(String paramName, String val) {
1478         if (TextUtils.isEmpty(val)) {
1479             throw new IllegalArgumentException(paramName + " can't be null");
1480         }
1481     }
1482
1483     /**
1484      * Get the DownloadProvider URI for the download with the given ID.
1485      *
1486      * @hide
1487      */
1488     public Uri getDownloadUri(long id) {
1489         return ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, id);
1490     }
1491
1492     /**
1493      * Get a parameterized SQL WHERE clause to select a bunch of IDs.
1494      */
1495     static String getWhereClauseForIds(long[] ids) {
1496         StringBuilder whereClause = new StringBuilder();
1497         whereClause.append("(");
1498         for (int i = 0; i < ids.length; i++) {
1499             if (i > 0) {
1500                 whereClause.append("OR ");
1501             }
1502             whereClause.append(Downloads.Impl._ID);
1503             whereClause.append(" = ? ");
1504         }
1505         whereClause.append(")");
1506         return whereClause.toString();
1507     }
1508
1509     /**
1510      * Get the selection args for a clause returned by {@link #getWhereClauseForIds(long[])}.
1511      */
1512     static String[] getWhereArgsForIds(long[] ids) {
1513         String[] whereArgs = new String[ids.length];
1514         return getWhereArgsForIds(ids, whereArgs);
1515     }
1516
1517     /**
1518      * Get selection args for a clause returned by {@link #getWhereClauseForIds(long[])}
1519      * and write it to the supplied args array.
1520      */
1521     static String[] getWhereArgsForIds(long[] ids, String[] args) {
1522         assert(args.length >= ids.length);
1523         for (int i = 0; i < ids.length; i++) {
1524             args[i] = Long.toString(ids[i]);
1525         }
1526         return args;
1527     }
1528
1529
1530     /**
1531      * This class wraps a cursor returned by DownloadProvider -- the "underlying cursor" -- and
1532      * presents a different set of columns, those defined in the DownloadManager.COLUMN_* constants.
1533      * Some columns correspond directly to underlying values while others are computed from
1534      * underlying data.
1535      */
1536     private static class CursorTranslator extends CursorWrapper {
1537         private final Uri mBaseUri;
1538         private final boolean mAccessFilename;
1539
1540         public CursorTranslator(Cursor cursor, Uri baseUri, boolean accessFilename) {
1541             super(cursor);
1542             mBaseUri = baseUri;
1543             mAccessFilename = accessFilename;
1544         }
1545
1546         @Override
1547         public int getInt(int columnIndex) {
1548             return (int) getLong(columnIndex);
1549         }
1550
1551         @Override
1552         public long getLong(int columnIndex) {
1553             if (getColumnName(columnIndex).equals(COLUMN_REASON)) {
1554                 return getReason(super.getInt(getColumnIndex(Downloads.Impl.COLUMN_STATUS)));
1555             } else if (getColumnName(columnIndex).equals(COLUMN_STATUS)) {
1556                 return translateStatus(super.getInt(getColumnIndex(Downloads.Impl.COLUMN_STATUS)));
1557             } else {
1558                 return super.getLong(columnIndex);
1559             }
1560         }
1561
1562         @Override
1563         public String getString(int columnIndex) {
1564             final String columnName = getColumnName(columnIndex);
1565             switch (columnName) {
1566                 case COLUMN_LOCAL_URI:
1567                     return getLocalUri();
1568                 case COLUMN_LOCAL_FILENAME:
1569                     if (!mAccessFilename) {
1570                         throw new SecurityException(
1571                                 "COLUMN_LOCAL_FILENAME is deprecated;"
1572                                         + " use ContentResolver.openFileDescriptor() instead");
1573                     }
1574                 default:
1575                     return super.getString(columnIndex);
1576             }
1577         }
1578
1579         private String getLocalUri() {
1580             long destinationType = getLong(getColumnIndex(Downloads.Impl.COLUMN_DESTINATION));
1581             if (destinationType == Downloads.Impl.DESTINATION_FILE_URI ||
1582                     destinationType == Downloads.Impl.DESTINATION_EXTERNAL ||
1583                     destinationType == Downloads.Impl.DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD) {
1584                 String localPath = super.getString(getColumnIndex(COLUMN_LOCAL_FILENAME));
1585                 if (localPath == null) {
1586                     return null;
1587                 }
1588                 return Uri.fromFile(new File(localPath)).toString();
1589             }
1590
1591             // return content URI for cache download
1592             long downloadId = getLong(getColumnIndex(Downloads.Impl._ID));
1593             return ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, downloadId).toString();
1594         }
1595
1596         private long getReason(int status) {
1597             switch (translateStatus(status)) {
1598                 case STATUS_FAILED:
1599                     return getErrorCode(status);
1600
1601                 case STATUS_PAUSED:
1602                     return getPausedReason(status);
1603
1604                 default:
1605                     return 0; // arbitrary value when status is not an error
1606             }
1607         }
1608
1609         private long getPausedReason(int status) {
1610             switch (status) {
1611                 case Downloads.Impl.STATUS_WAITING_TO_RETRY:
1612                     return PAUSED_WAITING_TO_RETRY;
1613
1614                 case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
1615                     return PAUSED_WAITING_FOR_NETWORK;
1616
1617                 case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
1618                     return PAUSED_QUEUED_FOR_WIFI;
1619
1620                 case Downloads.Impl.STATUS_PAUSED_MANUAL:
1621                     return PAUSED_MANUAL;
1622
1623                 default:
1624                     return PAUSED_UNKNOWN;
1625             }
1626         }
1627
1628         private long getErrorCode(int status) {
1629             if ((400 <= status && status < Downloads.Impl.MIN_ARTIFICIAL_ERROR_STATUS)
1630                     || (500 <= status && status < 600)) {
1631                 // HTTP status code
1632                 return status;
1633             }
1634
1635             switch (status) {
1636                 case Downloads.Impl.STATUS_FILE_ERROR:
1637                     return ERROR_FILE_ERROR;
1638
1639                 case Downloads.Impl.STATUS_UNHANDLED_HTTP_CODE:
1640                 case Downloads.Impl.STATUS_UNHANDLED_REDIRECT:
1641                     return ERROR_UNHANDLED_HTTP_CODE;
1642
1643                 case Downloads.Impl.STATUS_HTTP_DATA_ERROR:
1644                     return ERROR_HTTP_DATA_ERROR;
1645
1646                 case Downloads.Impl.STATUS_TOO_MANY_REDIRECTS:
1647                     return ERROR_TOO_MANY_REDIRECTS;
1648
1649                 case Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR:
1650                     return ERROR_INSUFFICIENT_SPACE;
1651
1652                 case Downloads.Impl.STATUS_DEVICE_NOT_FOUND_ERROR:
1653                     return ERROR_DEVICE_NOT_FOUND;
1654
1655                 case Downloads.Impl.STATUS_CANNOT_RESUME:
1656                     return ERROR_CANNOT_RESUME;
1657
1658                 case Downloads.Impl.STATUS_FILE_ALREADY_EXISTS_ERROR:
1659                     return ERROR_FILE_ALREADY_EXISTS;
1660
1661                 default:
1662                     return ERROR_UNKNOWN;
1663             }
1664         }
1665
1666         private int translateStatus(int status) {
1667             switch (status) {
1668                 case Downloads.Impl.STATUS_PENDING:
1669                     return STATUS_PENDING;
1670
1671                 case Downloads.Impl.STATUS_RUNNING:
1672                     return STATUS_RUNNING;
1673
1674                 case Downloads.Impl.STATUS_PAUSED_BY_APP:
1675                 case Downloads.Impl.STATUS_WAITING_TO_RETRY:
1676                 case Downloads.Impl.STATUS_WAITING_FOR_NETWORK:
1677                 case Downloads.Impl.STATUS_QUEUED_FOR_WIFI:
1678                 case Downloads.Impl.STATUS_PAUSED_MANUAL:
1679                     return STATUS_PAUSED;
1680
1681                 case Downloads.Impl.STATUS_SUCCESS:
1682                     return STATUS_SUCCESSFUL;
1683
1684                 default:
1685                     assert Downloads.Impl.isStatusError(status);
1686                     return STATUS_FAILED;
1687             }
1688         }
1689     }
1690 }