B4A Library DownloadManager

The B4A DownloadManager library enables you to use the Android DownloadManager in your projects.

DownloadManager requires a minimum Android API level of 9 (Gingerbread), some features of the library require higher API levels.
The SQL library must also be enabled in order to work with the DownloadManager Query method.


Here's the technical details:

DownloadManager
Comment: The download manager is a system service that handles long-running HTTP downloads.
Clients may request that a URI be downloaded to a particular destination file.
The download manager will conduct the download in the background,
taking care of HTTP interactions and retrying downloads after failures or across connectivity changes and system reboots.

Apps that request downloads through this API should register a broadcast receiver for
ACTION_NOTIFICATION_CLICKED to appropriately handle when the user clicks on a running download in a notification or from the downloads UI.
Note that the application must have the INTERNET permission to use this class.

DownloadManager is only available with Android API level 9+.
Version: 1.01
  • DownloadManager
    Events:
    • DownloadComplete (DownloadId As Long)
    • NotificationClicked (DownloadIds() As Long)
    Fields:
    • ACTION_DOWNLOAD_COMPLETE As String
      Broadcast intent action sent by the download manager when a download completes.
    • ACTION_NOTIFICATION_CLICKED As String
      Broadcast intent action sent by the download manager when the user clicks on a running download,
      either from a system notification or from the downloads UI.
    • ACTION_VIEW_DOWNLOADS As String
      Intent action to launch an activity to display all downloads.
    • COLUMN_BYTES_DOWNLOADED_SO_FAR As String
      Number of bytes downloaded so far.
    • COLUMN_DESCRIPTION As String
      The client-supplied description of this download.
    • COLUMN_ID As String
      An identifier for a particular download, unique across the system.
    • COLUMN_LAST_MODIFIED_TIMESTAMP As String
      Timestamp when the download was last modified in System.currentTimeMillis().
    • COLUMN_LOCAL_FILENAME As String
      The pathname of the file where the download is stored.
    • COLUMN_LOCAL_URI As String
      Uri where downloaded file will be stored.
    • COLUMN_MEDIAPROVIDER_URI As String
      The URI to the corresponding entry in MediaProvider for this downloaded entry.
    • COLUMN_MEDIA_TYPE As String
      Internet Media Type of the downloaded file.
    • COLUMN_REASON As String
      Provides more detail on the status of the download.
    • COLUMN_STATUS As String
      Current status of the download, as one of the STATUS_* constants.
    • COLUMN_TITLE As String
      The client-supplied title for this download.
    • COLUMN_TOTAL_SIZE_BYTES As String
      Total size of the download in bytes.
    • COLUMN_URI As String
      URI to be downloaded.
    • ERROR_CANNOT_RESUME As Int
      Value of COLUMN_REASON when some possibly transient error occurred but we cannot resume the download.
    • ERROR_DEVICE_NOT_FOUND As Int
      Value of COLUMN_REASON when no external storage device was found.
    • ERROR_FILE_ALREADY_EXISTS As Int
      Value of COLUMN_REASON when the requested destination file already exists.
      (The DownloadManager will not overwrite an existing file).
    • ERROR_FILE_ERROR As Int
      Value of COLUMN_REASON when a storage issue arises which doesn't fit under any other error code.
    • ERROR_HTTP_DATA_ERROR As Int
      Value of COLUMN_REASON when an error receiving or processing data occurred at the HTTP level.
    • ERROR_INSUFFICIENT_SPACE As Int
      Value of COLUMN_REASON when there was insufficient storage space.
    • ERROR_TOO_MANY_REDIRECTS As Int
      Value of COLUMN_REASON when there were too many redirects.
    • ERROR_UNHANDLED_HTTP_CODE As Int
      Value of COLUMN_REASON when an HTTP code was received that download manager can't handle.
    • ERROR_UNKNOWN As Int
      Value of COLUMN_ERROR_CODE when the download has completed with an error that doesn't fit under any other error code.
    • EXTRA_DOWNLOAD_ID As String
      Intent extra included with ACTION_DOWNLOAD_COMPLETE intents,
      indicating the ID (as a long) of the download that just completed.
    • EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS As String
      When clicks on multiple notifications are received, the following provides
      an array of download ids corresponding to the download notifications that were clicked.
    • INTENT_EXTRAS_SORT_BY_SIZE As String
      Intent extra included with ACTION_VIEW_DOWNLOADS to start DownloadApp in sort-by-size mode.
    • PAUSED_QUEUED_FOR_WIFI As Int
      Value of COLUMN_REASON when the download exceeds a size limit for downloads
      over the mobile network and the download manager is waiting for a Wi-Fi connection to proceed.
    • PAUSED_UNKNOWN As Int
      Value of COLUMN_REASON when the download is paused for some other reason.
    • PAUSED_WAITING_FOR_NETWORK As Int
      Value of COLUMN_REASON when the download is waiting for network connectivity to proceed.
    • PAUSED_WAITING_TO_RETRY As Int
      Value of COLUMN_REASON when the download is paused because some network error occurred
      and the download manager is waiting before retrying the request.
    • STATUS_FAILED As Int
      Value of COLUMN_STATUS when the download has failed (and will not be retried).
    • STATUS_PAUSED As Int
      Value of COLUMN_STATUS when the download is waiting to retry or resume.
    • STATUS_PENDING As Int
      Value of COLUMN_STATUS when the download is waiting to start.
    • STATUS_RUNNING As Int
      Value of COLUMN_STATUS when the download is currently running.
    • STATUS_SUCCESSFUL As Int
      Value of COLUMN_STATUS when the download has successfully completed.
    Methods:
    • AddCompletedDownload (Title As String, Description As String, IsMediaScannerScannable As Boolean, MimeType As String, Path As String, Length As Long, ShowNotification As Boolean)
      Adds a file to the downloads database system, so it could appear in Downloads App (and thus become eligible for management by the Downloads App).

      It is helpful to make the file scanable by MediaScanner by setting the param IsMediaScannerScannable to true.
      It makes the file visible in media managing applications such as Gallery App, which could be a useful purpose of using this method.

      Only available with Android API level 12+.
    • Enqueue (Request1 As Request) As Long
      Enqueue a new download.
      The download will start automatically once the download manager is ready to execute it and connectivity is available.

      Returns a DownloadId for the download entry added to the downloads app, unique across the system.
      This DownloadId is used to make future calls related to this download.
    • GetMaxBytesOverMobile As Long
      Returns maximum size, in bytes, of downloads that may go over a mobile connection or Null if there is no limit.

      Only available with Android API level 11+.
    • GetMimeTypeForDownloadedFile (DownloadId As Long) As String
      Get the mime type of the download identified by DownloadId.

      Only available with Android API level 11+.
    • GetRecommendedMaxBytesOverMobile As Long
      Returns recommended maximum size, in bytes, of downloads that may go over a mobile connection or Null if there's no recommended limit.
      The user will have the option to bypass this limit.

      Only available with Android API level 11+.
    • Query (Query1 As Query) As CursorWrapper
      Query the download manager about downloads that have been requested.

      Requires the SQL library to be enabled.
    • RegisterReceiver (EventName As String)
      Registers a BroadcastReceiver to receive broadcasts for ACTION_DOWNLOAD_COMPLETE and ACTION_NOTIFICATION_CLICKED.
      DownloadManager will now raise events DownloadComplete(DownloadId As Long) and NotificationClicked(DownloadIds() As Long).
      Be sure to call the UnregisterReceiver method when your Activity exits or Service is destroyed to free system resources.
    • Remove (DownloadId As Long) As Int
      Cancels the download identified by DownloadId and removes it from the download manager.
    • Remove2 (DownloadIds() As Long) As Int
      Cancels the downloads identified by DownloadIds and removes them from the download manager.
    • RenameFile (SourcePath As String, SourceFilename As String, DestinationPath As String, DestinationFilename As String) As Boolean
    • UnregisterReceiver
      Unregister the BroadcastReceiver if it has been registered.
    Permissions:
    • android.permission.INTERNET
  • DownloadManagerQuery
    Methods:
    • Initialize
    • IsInitialized As Boolean
    • SetFilterById (DownloadId As Long)
      Include only the download with the given DownloadId.
    • SetFilterById2 (DownloadIds() As Long)
      Include only the downloads with the given DownloadIds.
    • SetFilterByStatus (Status As Int)
      Include only downloads with status matching any the given Status flags.
  • DownloadManagerRequest
    Fields:
    • NETWORK_MOBILE As Int
    • NETWORK_WIFI As Int
    • VISIBILITY_HIDDEN As Int
      This download doesn't show in the UI or in the notifications.

      Only available with Android API level 11+.
    • VISIBILITY_VISIBLE As Int
      This download is visible but only shows in the notifications while it's in progress.

      Only available with Android API level 11+.
    • VISIBILITY_VISIBLE_NOTIFY_COMPLETED As Int
      This download is visible and shows in the notifications while in progress and after completion.

      Only available with Android API level 11+.
    • VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION As Int
      This download shows in the notifications after completion ONLY.
      It is usable only with the DownloadManager AddCompletedDownload method.

      Only available with Android API level 12+.
    Methods:
    • AddRequestHeader (Header As String, Value As String)
      Add an HTTP header to be included with the download request.
    • AllowScanningByMediaScanner
      The file to be downloaded is to be scanned by MediaScanner.
      This method should be called before enqueue(Request) is called.

      Only available with Android API level 11+.
    • Initialize (Uri1 As String)
      Initialize the Request object with the Uri of the file to be downloaded.
    • IsInitialized As Boolean
    • SetDestinationInExternalFilesDir (DirType As String, SubPath As String)
      Set the local destination for the downloaded file to a path within the application's external files directory.
      DirType - Documentation required... (Pass Null for default action).
      SubPath - The path within the external directory, including the destination filename.
    • SetDestinationInExternalPublicDir (DirType As String, SubPath As String)
      Set the local destination for the downloaded file to a path within the public external storage directory.
      DirType - Documentation required... (Pass Null for default action).
      SubPath - The path within the external directory, including the destination filename.
    Properties:
    • AllowedNetworkTypes As Int [write only]
      Restrict the types of networks over which this download may proceed.
    • AllowedOverMetered As Boolean [write only]
      Set whether this download may proceed over a metered network connection.
      By default, metered networks are allowed.

      Only available with Android API level 16+.
    • AllowedOverRoaming As Boolean [write only]
      Set whether this download may proceed over a roaming connection.
      By default, roaming is allowed.
    • Description As String [write only]
      Set a description of this download, to be displayed in notifications (if enabled).
    • DestinationUri As String [write only]
      Set the local destination for the downloaded file.
      Must be a file Uri to a path on external storage, and the calling application must have the WRITE_EXTERNAL_STORAGE permission.

      By default, downloads are saved to a generated filename in the shared download cache and may be deleted by the system at any time to reclaim space.
    • MimeType As String [write only]
      Set the MIME content type of this download.
    • NotificationVisibility As Int [write only]
      Control whether a system notification is posted by the download manager while this download is running or when it is completed.
      If enabled, the download manager posts notifications about downloads through the system NotificationManager.
      By default, a notification is shown only when the download is in progress.

      If set to VISIBILITY_HIDDEN, this requires the permission android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.

      Only available with Android API level 11+.
    • ShowRunningNotification As Boolean [write only]
      Control whether a system notification is posted by the download manager while this download is running.
      If enabled, the download manager posts notifications about downloads through the system NotificationManager.
      By default, a notification is shown.
      If set to false, this requires the permission android.permission.DOWNLOAD_WITHOUT_NOTIFICATION.

      This method was deprecated in API level 11.
    • Title As String [write only]
      Set the title of this download, to be displayed in notifications (if enabled).
    • VisibleInDownloadsUi As Boolean [write only]
      Set whether this download should be displayed in the system's Downloads UI.

The DownloadManager tutorial thread can be found here: http://www.b4x.com/forum/basic4andr...2307-downloadmanager-tutorial.html#post129467

Martin.
 

Attachments

  • DownloadManager_v1.01.zip
    16.3 KB · Views: 1,729
Last edited:

susu

Well-Known Member
Licensed User
Longtime User
Thank you for your sharing, Maritn :D
 

Djembefola

Active Member
Licensed User
Longtime User
Wow, this is a great library. (And a great tutorial, by the way)
Thank you for your work.
:sign0098:

DownloadManager requires a minimum Android API level of 9 (Gingerbread), some features of the library require higher API levels.

API Level 9 would be ok for me, but i need to make sure that downloads proceed only as long as a wifi connection is established.

I have seen this property in the Documentation:
AllowedNetworkTypes As Int [write only]
Restrict the types of networks over which this download may proceed.

Only available with Android API level 11+.

Is there any way to restrict the network type on a Gingerbread device?
Can i add this functionality with b4a?
 

warwound

Expert
Licensed User
Longtime User
DownloadManager updated to version 1.01

:signOops:

My mistake in the documentation there - the native Android setAllowedNetworkTypes() method is available with API level 9+.
So that's corrected with this update.

Checking through the rest of the documentation i saw that API level 9 also supports the method setShowRunningNotification (boolean show).
This method became deprecated from API level 11+, replaced with the setNotificationVisibility (int visibility) method.

So i've added the setShowRunningNotification method to the library as part of this update too.
Check the updated reference in the first post, if you intend to use this method as it requires a new permission to be added to your app.

Version 1.01 is attached to the first post in this thread.

Martin.
 
Top