Android Tutorial DownloadManager tutorial

Here i'll post one or two examples showing how to use the DownloadManager library.

DownloadManager simple example.
Here's what must be the most simple way to use DownloadManager.
It shows usage of all three DownloadManager objects:
  • DownloadManager the main library object.
  • DownloadManagerRequest an object used to create a new download request.
  • DownloadManagerQuery an object used to query the DownloadManager for the status of a DownloadRequest.

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

B4X:
Sub Process_Globals

   Dim DOWNLOAD_ADDRESS As String="http://www.b4x.com/android/images/wiki_logo.png"
   Dim DOWNLOAD_FILENAME As String="wiki_logo.png"
   
   '   DownloadId is a unique identifier assigned by the DownloadManager to this download task
   Dim DownloadId As Long
   
End Sub

Sub Globals
   
   Dim DownloadButton As Button
   Dim DownloadManager1 As DownloadManager
   
   Dim ImageView1 As ImageView
End Sub

Sub Activity_Create(FirstTime As Boolean)
   Activity.LoadLayout("Main")
   
   '   RegisterReceiver enables DownloadManager to raise events
   DownloadManager1.RegisterReceiver("DownloadManager1")
   
   '   Utils is a helper code module
   If Utils.IsInitialized=False Then
      Utils.Initialize(DownloadManager1)
   End If
   
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub DownloadButton_Click

   Dim DownloadManagerRequest1 As DownloadManagerRequest
   DownloadManagerRequest1.Initialize(DOWNLOAD_ADDRESS)
   DownloadManagerRequest1.Description="DownloadManager demo"
   '   save the download to external memory
   '   note you must manually update your project's manifest file adding android.permission.WRITE_EXTERNAL_STORAGE
   DownloadManagerRequest1.DestinationUri="file://"&File.Combine(File.DirRootExternal, DOWNLOAD_FILENAME)
   DownloadManagerRequest1.Title=DOWNLOAD_FILENAME
   DownloadManagerRequest1.VisibleInDownloadsUi=True
   
   DownloadId=DownloadManager1.Enqueue(DownloadManagerRequest1)
End Sub

Sub DownloadManager1_DownloadComplete(DownloadId1 As Long)
   '   this does not guarantee that the download has actually successfully downloaded
   '   it means a DownloadMananger DownloadManagerRequest has completed
   '   we need to find that status of that request but only if that request matches the request we started
   
   If DownloadId=DownloadId1 Then
      '   this is the download request we started
      '   query the DownloadManager for info on this request
      Dim DownloadManagerQuery1 As DownloadManagerQuery
      DownloadManagerQuery1.Initialize
      DownloadManagerQuery1.SetFilterById(DownloadId)
      
      '   you must enable the SQL library to work with the Cursor object
      Dim StatusCursor As Cursor
      '   pass our DownloadManagerQuery to the DownloadManager
      StatusCursor=DownloadManager1.Query(DownloadManagerQuery1)
      If StatusCursor.RowCount>0 Then
         StatusCursor.Position=0   
         
         Dim StatusInt As Int
         StatusInt=StatusCursor.getInt(DownloadManager1.COLUMN_STATUS)
         Log("Download Status = "&Utils.GetStatusText(StatusInt))

         If StatusInt=DownloadManager1.STATUS_FAILED OR StatusInt=DownloadManager1.STATUS_PAUSED Then
            Dim ReasonInt As Int
            ReasonInt=StatusCursor.GetInt(DownloadManager1.COLUMN_REASON)
            Log("Status Reason = "&Utils.GetReasonText(ReasonInt))
         End If
         
         If StatusInt=DownloadManager1.STATUS_SUCCESSFUL Then
            ImageView1.Bitmap=LoadBitmap(File.DirRootExternal, DOWNLOAD_FILENAME)
         End If
         
      Else
         '   always check that the Cursor returned from the DownloadManager Query method is not empty
         Log("The DownloadManager has no trace of our request, it could have been cancelled by the user using the Android Downloads app or an unknown error has occurred.")
      End If
      
      '   free system resources
      StatusCursor.Close
      DownloadManager1.UnregisterReceiver
   End If
   
End Sub

DownloadManager requires android.permission.INTERNET and this is automatically added to your manifest when you use the library.
Saving downloads to external storage requires android.permission.WRITE_EXTERNAL_STORAGE, this must be manually added to your manifest using the manifest editor.
Here's the line i added to this example's manifest file:

B4X:
AddPermission(android.permission.WRITE_EXTERNAL_STORAGE)

The example downloads an image to external memory and displays it in an ImageView.
Not very exciting but it shows you basic syntax and usage etc.

I'll create some more advanced examples tomorrow hopefully and post them in this thread.

Martin.
 

Attachments

  • simple_example.zip
    8.6 KB · Views: 2,110
Last edited:

warwound

Expert
Licensed User
Longtime User
DownloadManager using a service

Now the reason you're likely to be using DownloadManager is because you want to download and resume download of (large) files where the download process is not a part of your app's life cycle.
Handling DownloadManager in an Activity is not suitable for this - if the user closes your app or reboots their device you'll not be able to handle the completion of the download request nor clicks on the DownloadMananger notification.
The solution is to handle the DownloadManager within a service module.

This example will do the same as the previous simple example but use a service module to handle the DownloadManager.
The Activity is now very simple:

B4X:
Sub Process_Globals
   
End Sub

Sub Globals
   Dim DownloadButton As Button
   Dim DownloadManager1 As DownloadManager
   Dim ImageView1 As ImageView
End Sub

Sub Activity_Create(FirstTime As Boolean)
   Activity.LoadLayout("Main")
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub DownloadButton_Click
   StartService(DownloaderService)
End Sub

Sub ShowBitmap(Bitmap1 As Bitmap)
   ImageView1.Bitmap=Bitmap1
End Sub

A click on the button starts the DownloaderService, where you'll see most of the code is identical to the previous simple example code:

B4X:
Sub Process_Globals
   Dim DOWNLOAD_ADDRESS As String="http://www.b4x.com/android/images/wiki_logo.png"
   Dim DOWNLOAD_FILENAME As String="wiki_logo.png"
   
   '   DownloadId is a unique identifier assigned by the DownloadManager to this download task
   Dim DownloadId As Long
   Dim DownloadManager1 As DownloadManager
End Sub

Sub Service_Create
   '   RegisterReceiver enables DownloadManager to raise events
   DownloadManager1.RegisterReceiver("DownloadManager1")
   
   '   Utils is a helper code module
   If Utils.IsInitialized=False Then
      Utils.Initialize(DownloadManager1)
   End If
End Sub

Sub Service_Start (StartingIntent As Intent)
   Dim DownloadManagerRequest1 As DownloadManagerRequest
   DownloadManagerRequest1.Initialize(DOWNLOAD_ADDRESS)
   DownloadManagerRequest1.Description="DownloadManager demo"
   '   save the download to external memory
   '   note you must manually update your project's manifest file adding android.permission.WRITE_EXTERNAL_STORAGE
   DownloadManagerRequest1.DestinationUri="file://"&File.Combine(File.DirRootExternal, DOWNLOAD_FILENAME)
   DownloadManagerRequest1.Title=DOWNLOAD_FILENAME
   DownloadManagerRequest1.VisibleInDownloadsUi=True
   
   DownloadId=DownloadManager1.Enqueue(DownloadManagerRequest1)
End Sub

Sub Service_Destroy
   '   by unregistering the BroadcastReceiver the DownloadManager will no longer raise events
   DownloadManager1.UnregisterReceiver
End Sub

Sub DownloadManager1_DownloadComplete(DownloadId1 As Long)
   '   this does not guarantee that the download has actually successfully downloaded
   '   it means a DownloadMananger DownloadManagerRequest has completed
   '   we need to find that status of that request but only if that request matches the request we started
   
   If DownloadId=DownloadId1 Then
      '   this is the download request we started
      '   query the DownloadManager for info on this request
      Dim DownloadManagerQuery1 As DownloadManagerQuery
      DownloadManagerQuery1.Initialize
      DownloadManagerQuery1.SetFilterById(DownloadId)
      
      '   you must enable the SQL library to work with the Cursor object
      Dim StatusCursor As Cursor
      '   pass our DownloadManagerQuery to the DownloadManager
      StatusCursor=DownloadManager1.Query(DownloadManagerQuery1)
      If StatusCursor.RowCount>0 Then
         StatusCursor.Position=0   
         
         Dim StatusInt As Int
         StatusInt=StatusCursor.getInt(DownloadManager1.COLUMN_STATUS)
         Log("Download Status = "&Utils.GetStatusText(StatusInt))

         If StatusInt=DownloadManager1.STATUS_FAILED OR StatusInt=DownloadManager1.STATUS_PAUSED Then
            Dim ReasonInt As Int
            ReasonInt=StatusCursor.GetInt(DownloadManager1.COLUMN_REASON)
            Log("Status Reason = "&Utils.GetReasonText(ReasonInt))
         End If
         
         If StatusInt=DownloadManager1.STATUS_SUCCESSFUL Then
            CallSub2(Main, "ShowBitmap", LoadBitmap(File.DirRootExternal, DOWNLOAD_FILENAME))
         End If
      Else
         '   always check that the Cursor returned from the DownloadManager Query method is not empty
         Log("The DownloadManager has no trace of our request, it could have been cancelled by the user using the Android Downloads app or an unknown error has occurred.")
      End If
      
      StatusCursor.Close
      StopService("")
   End If
End Sub

Sub DownloadManager1_NotificationClicked(DownloadIds() As Long)
   '   this event will be raised if the user clicks the DownloadManager notification
   '   if the device Android API level is 11 or higher then DownloadIds will be an array of download request ids.
   '   onlower API levels DownloadIds will be Null
   
   Log("DownloadManager1_NotificationClicked our download request is: "&DownloadId)
   If DownloadIds<>Null Then
      Log("DownloadIds length is: "&DownloadIds.Length)
      Dim i As Int
      For i=0 To DownloadIds.Length-1
         Log("DownloadIds("&i&")="&DownloadIds(i))
      Next
   Else
      Log("DownloadIds is Null")
   End If
End Sub

If the download request is successful then CallSub2 is used to call an Activity Sub, passing the downloaded Bitmap as a parameter.

You can see that i've also created a Sub to handle the DownloadManager NotificationClicked event.
Be sure to read the Sub comments - older versions of Android do NOT pass this event an array of ids of the clicked notifications.

Martin.
 

Attachments

  • simple_service_example.zip
    9.4 KB · Views: 1,070

warwound

Expert
Licensed User
Longtime User
Register your application as a DownloadManager BroadcastReceiver

The previous examples received the DownloadManager ACTION_DOWNLOAD_COMPLETE and ACTION_NOTIFICATION_CLICKED broadcasts because we used the RegisterReceiver method to register the Activity or Service as a receiver.
This works fine BUT what to do if you want your application to receive these broadcasts even if it is not running?

The answer is to register your application as a BroadcastReceiver for DownloadManager broadcasts by editing the manifest file.
Now whenever any DownloadManager request completes or a DownloadManager notification is clicked, your application will receive an ACTION_DOWNLOAD_COMPLETE or ACTION_NOTIFICATION_CLICKED broadcast.
You can register your application as a BroadcastReceiver for both or either broadcasts.

Here's the syntax to register your application for both broadcasts:

B4X:
AddReceiverText(MyServiceName, <intent-filter>
<action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
<action android:name="android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED" />
</intent-filter>)

Whenever a DownloadManager request completes or notification is clicked, the Android OS will start the service name MyServiceName, so you want to change that to match the name of your application's service.
In this example code the service to register is named DownloaderService.

The activity code for this example is identical to the previous DownloadManager using a service example, the DownloaderService code is different of course:

B4X:
Sub Process_Globals
   Dim DOWNLOAD_ADDRESS As String="http://www.b4x.com/android/images/wiki_logo.png"
   Dim DOWNLOAD_FILENAME As String="wiki_logo.png"
   
   '   DownloadId is a unique identifier assigned by the DownloadManager to this download task
   Dim DownloadId As Long
   Dim DownloadManager1 As DownloadManager
End Sub

Sub Service_Create
   '   removed the code to call the DownloadManager RegisterReceiver method
   
   '   Utils is a helper code module
   If Utils.IsInitialized=False Then
      Utils.Initialize(DownloadManager1)
   End If
End Sub

Sub Service_Start (StartingIntent As Intent)

   Select StartingIntent.Action
      Case DownloadManager1.ACTION_DOWNLOAD_COMPLETE
         HandleDownloadComplete(StartingIntent)
      Case DownloadManager1.ACTION_NOTIFICATION_CLICKED
         HandleNotificationClicked(StartingIntent)
      Case Else
         '   the service has not been started by a DownloadManager broadcast
         '   it must have been started by a button click in the Main Activity
         '   so we'll start a new download request
         Dim DownloadManagerRequest1 As DownloadManagerRequest
         DownloadManagerRequest1.Initialize(DOWNLOAD_ADDRESS)
         DownloadManagerRequest1.Description="DownloadManager demo"
         '   save the download to external memory
         '   note you must manually update your project's manifest file adding android.permission.WRITE_EXTERNAL_STORAGE
         DownloadManagerRequest1.DestinationUri="file://"&File.Combine(File.DirRootExternal, DOWNLOAD_FILENAME)
         DownloadManagerRequest1.Title=DOWNLOAD_FILENAME
         DownloadManagerRequest1.VisibleInDownloadsUi=True
         
         DownloadId=DownloadManager1.Enqueue(DownloadManagerRequest1)
         '   we can now stop the service, it will be restarted whenever a download request completes
         StopService("")
   End Select
   
End Sub

Sub Service_Destroy
   '   removed the code to call the DownloadManager UnregisterReceiver method
End Sub

Sub HandleDownloadComplete(StartingIntent As Intent)
   '   the Intent that started this service contains all the info we need
   Dim DownloadId1 As Long
   DownloadId1=StartingIntent.GetExtra(DownloadManager1.EXTRA_DOWNLOAD_ID)
   
   If DownloadId=DownloadId1 Then
      '   this is the download request we started
      '   query the DownloadManager for info on this request
      Dim DownloadManagerQuery1 As DownloadManagerQuery
      DownloadManagerQuery1.Initialize
      DownloadManagerQuery1.SetFilterById(DownloadId)
      
      '   you must enable the SQL library to work with the Cursor object
      Dim StatusCursor As Cursor
      '   pass our DownloadManagerQuery to the DownloadManager
      StatusCursor=DownloadManager1.Query(DownloadManagerQuery1)
      If StatusCursor.RowCount>0 Then
         StatusCursor.Position=0   
         
         Dim StatusInt As Int
         StatusInt=StatusCursor.getInt(DownloadManager1.COLUMN_STATUS)
         Log("Download Status = "&Utils.GetStatusText(StatusInt))

         If StatusInt=DownloadManager1.STATUS_FAILED OR StatusInt=DownloadManager1.STATUS_PAUSED Then
            Dim ReasonInt As Int
            ReasonInt=StatusCursor.GetInt(DownloadManager1.COLUMN_REASON)
            Log("Status Reason = "&Utils.GetReasonText(ReasonInt))
         End If
         
         If StatusInt=DownloadManager1.STATUS_SUCCESSFUL Then
            CallSub2(Main, "ShowBitmap", LoadBitmap(File.DirRootExternal, DOWNLOAD_FILENAME))
         End If
      Else
         '   always check that the Cursor returned from the DownloadManager Query method is not empty
         Log("The DownloadManager has no trace of our request, it could have been cancelled by the user using the Android Downloads app or an unknown error has occurred.")
      End If
      
      StatusCursor.Close
      StopService("")
   End If
   
End Sub

Sub HandleNotificationClicked(StartingIntent As Intent)
   '   the Intent that started this service contains all the info we need
   Dim DownloadIds() As Long
   DownloadIds=StartingIntent.GetExtra(DownloadManager1.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS)
   
   Log("HandleNotificationClicked our download request is: "&DownloadId)
   If DownloadIds<>Null Then
      Log("DownloadIds length is: "&DownloadIds.Length)
      Dim i As Int
      For i=0 To DownloadIds.Length-1
         Log("DownloadIds("&i&")="&DownloadIds(i))
      Next
   Else
      Log("DownloadIds is Null")
   End If
End Sub

The service starts and checks the Intent that started it.
From there it knows whether it has been started to handle a DownloadManager broadcast or whether it was started by the user clicking the Activity Button.

The code is much like the previous example, in this example we have to get the download request id or notifications clicked ids from the Intent that started the service.
In previous examples these ids were passed as parameters to the Event Subs.

You might like to change the URL of the download request to point to a non-existent file and watch the logs to see what's reported.
You could also change the URL to point to a large file to give you time to click the notification - change it to point to a large non-image file and comment out the CallSub2 statement to avoid exceptions when the download completes.

And be sure to start your device's Download app and see all of your download requests listed there - from here you can delete/clear/cancel downloads.

That's the basics of DownloadManager covered.
Next i'll show you how to create a service that is of use in the real world - but first time for a break!

Martin.
 

Attachments

  • register_app_as_broadcast_receiver.zip
    9.7 KB · Views: 908

future21

Member
Licensed User
Longtime User
Error DownloadManager

Hi. -

I tried to compile this example but I reported the following error:

B4X:
Compiling code. 0.15
Compiling code layouts. 0.15
Generating R file. 0.47
Compiling generated Java code. error
B4A line: 53
DownloadId = DownloadManager1.Enqueue (DownloadManagerRequest1)
javac 1.7.0_04
src \ uk \ co \ martinpearman \ B4A \ downloadmanagerdemo \ Main.java: 319: error: package does not exist android.app.DownloadManager
_downloadid =
****************************************************************************************** ^
1 error

I can compile it without errors?

Thank you.
 

warwound

Expert
Licensed User
Longtime User
I'd guess that in the B4A IDE you have the path to the android SDK set to a level lower than the required API level 9.

In the IDE click Tools > Configure Paths.
Look at the location of the android.jar, mine is set to API level 15:

I:\Program Files (x86)\Android\android-sdk\platforms\android-15\android.jar

Choose level 9 or higher.

Martin.
 

future21

Member
Licensed User
Longtime User
I'd guess that in the B4A IDE you have the path to the android SDK set to a level lower than the required API level 9.

In the IDE click Tools > Configure Paths.
Look at the location of the android.jar, mine is set to API level 15:



Choose level 9 or higher.

Martin.

Hello.

Thank you very much. I had not noticed that detail. Indeed, that was the mistake.

Greetings.
 

future21

Member
Licensed User
Longtime User
Hello.-

First, thanks for your great work with this library.

I have a doubt regarding its use, and do not know what is the way to download URL's protected with login and password, I can not find the variable for this data set.

Greetings and thank you very much.

Javier.
 

warwound

Expert
Licensed User
Longtime User
Are the download files protected by basic HTTP authentication?

Look at the DownloadManagerRequest method AddRequestHeader.
Can you set a header that'll allow the download?

There seems to be little documentation as to whether or not the DownloadManager supports download from password protected websites, take a look at this Google search.

The downloads could be protected by basic HTTP authentication, or they could be protected by a webpage with a form that requires a login and then a session cookie is set to allow downloads.

Can you post some more info about how the downloads are protected?
If you were to download these files using a browser how would the website prompt you for a username and password?

Martin.
 

future21

Member
Licensed User
Longtime User
Hello. -

The HTTP authentication is set to basic. For example, if I send in class HTTPUtils2Service Job.Username and Job.Password properties, I can connect to the server without problem.

Greetings and thank you very much.
 

warwound

Expert
Licensed User
Longtime User
Can you try to download the file using the stock Android browser?
Do you get prompted for a username/password?
If so does the browser then pass the download task to the DownloadManager (not this B4A wrapper of the DownloadManager)?
And again - if so - does the DownloadManager succeed or fail?

I've found this page: Android and the HTTP download file headers | DigiBlog
That sums up a lot of the known problems.

The main problem seems to be that the DownloadManager was not written with basic authentication in mind so success seems to be a hit or miss affair.

Anyway try using the stock Android browser to download the file and report your results - be sure to include what Android API level your device uses.

Martin.
 

future21

Member
Licensed User
Longtime User
In the browser (Chrome), not asking login and password when trying to recover files ....

Using DownloadManagerRequest1.AddRequestHeader ("Authorization", "Basic MTIyO ........ other Base64 password.") Would thus be the right way to send the HTTP header? I'm getting an error in the application in which it leaves suddenly reports no errors just as earlier sent HTTP header.

Greetings and thanks.
 
Last edited:

warwound

Expert
Licensed User
Longtime User
Well here's the rather brief official documentation for the DownloadManager.request addRequestHeader() method: DownloadManager.Request | Android Developers
It doesn't go into detail!
And the HTTP/1.1 Message Headers link in that documentation contains no specific info.

Is the URL you are trying to download a direct link to a file or a link to a script?
If it's a link to script that (after successful authentication) redirects to the file then that may be unsupported, have a read of this thread: file download - Android DownloadManager not working when redirected - Stack Overflow
That thread does imply that others have had success authenticating and downloading a file using DownloadManager so there must be a solution...

Another thread to read here: https://groups.google.com/forum/?fromgroups=#!topic/android-developers/P8-9687YIcY

That thread repeats something i've read while researching this - it seems as though the DownloadManager successfully authenticates with an initial HttpRequest, then issues another HttpRequest to get the download BUT that second HttpRequest does not contain the authenticated header and fails.
That thread also reports that the Authorization header value must be the Base64 encoded value of the String "usernamehere:passwordhere".

Is that the same format of the Authorization header that you are currently trying to use?
For a test could you try using a download URL of the format:

http://usernamehere:p[email protected]/file_to_download.zip

Does that work?
And what version(s) of Android are you running this code on?

Martin.
 

future21

Member
Licensed User
Longtime User
Well here's the rather brief official documentation for the DownloadManager.request addRequestHeader() method: DownloadManager.Request | Android Developers
It doesn't go into detail!
And the HTTP/1.1 Message Headers link in that documentation contains no specific info.

Is the URL you are trying to download a direct link to a file or a link to a script?
If it's a link to script that (after successful authentication) redirects to the file then that may be unsupported, have a read of this thread: file download - Android DownloadManager not working when redirected - Stack Overflow
That thread does imply that others have had success authenticating and downloading a file using DownloadManager so there must be a solution...

Another thread to read here: https://groups.google.com/forum/?fromgroups=#!topic/android-developers/P8-9687YIcY

That thread repeats something i've read while researching this - it seems as though the DownloadManager successfully authenticates with an initial HttpRequest, then issues another HttpRequest to get the download BUT that second HttpRequest does not contain the authenticated header and fails.
That thread also reports that the Authorization header value must be the Base64 encoded value of the String "usernamehere:passwordhere".

Is that the same format of the Authorization header that you are currently trying to use?
For a test could you try using a download URL of the format:



Does that work?
And what version(s) of Android are you running this code on?

Martin.


Hello again.

I'm afraid I am taking this issue the wrong way, I just checked you do not need the pair of login and password to access. Look at my code please, if you have a minute:

B4X:
Sub Service_Start (StartingIntent As Intent)
   Dim DownloadManagerRequest1 As DownloadManagerRequest
   'DownloadManagerRequest1.AddRequestHeader("Authorization: ", "Basic MTIyOTkxMkBhcnViYS5pdDozZmVid3luZ3lz")
   DownloadManagerRequest1.Initialize(DOWNLOAD_ADDRESS)
   'DownloadManagerRequest1.Description="DownloadManager demo"
   '   save the download to external memory
   '   note you must manually update your project's manifest file adding android.permission.WRITE_EXTERNAL_STORAGE
   DownloadManagerRequest1.DestinationUri="file://"&File.Combine(File.DirRootExternal, DOWNLOAD_FILENAME)
   DownloadManagerRequest1.Title=DOWNLOAD_FILENAME
   DownloadManagerRequest1.VisibleInDownloadsUi=True
   
   DownloadId=DownloadManager1.Enqueue(DownloadManagerRequest1)

   File.MakeDir(File.DirInternalCache, "Nuked")
   
   Dim Reader As TextReader
   Reader.Initialize(File.OpenInput(File.DirRootExternal, DOWNLOAD_FILENAME))
   line = Reader.ReadLine
   Do While line <> Null
      'Log(line)

      DownloadManagerRequest1.DestinationUri="file://"&File.Combine(File.DirInternalCache & "/Nuked", line)
      DownloadManagerRequest1.Title=line
      DownloadManagerRequest1.VisibleInDownloadsUi=True

      line = Reader.ReadLine
    Loop
    Reader.Close 
End Sub


B4X:
Sub DownloadManager1_DownloadComplete(DownloadId1 As Long)
   '   this does not guarantee that the download has actually successfully downloaded
   '   it means a DownloadMananger DownloadManagerRequest has completed
   '   we need to find that status of that request but only if that request matches the request we started
   
   If DownloadId=DownloadId1 Then
      '   this is the download request we started
      '   query the DownloadManager for info on this request
      Dim DownloadManagerQuery1 As DownloadManagerQuery
      DownloadManagerQuery1.Initialize
      DownloadManagerQuery1.SetFilterById(DownloadId)
      
      '   you must enable the SQL library to work with the Cursor object
      Dim StatusCursor As Cursor
      '   pass our DownloadManagerQuery to the DownloadManager
      StatusCursor=DownloadManager1.Query(DownloadManagerQuery1)
      If StatusCursor.RowCount>0 Then
         StatusCursor.Position=0   
         
         Dim StatusInt As Int
         StatusInt=StatusCursor.getInt(DownloadManager1.COLUMN_STATUS)
         Log("Download Status = "&Utils.GetStatusText(StatusInt))

         If StatusInt=DownloadManager1.STATUS_FAILED OR StatusInt=DownloadManager1.STATUS_PAUSED Then
            Dim ReasonInt As Int
            ReasonInt=StatusCursor.GetInt(DownloadManager1.COLUMN_REASON)
            Log("Status Reason = "&Utils.GetReasonText(ReasonInt))
         End If
         
         If StatusInt=DownloadManager1.STATUS_SUCCESSFUL Then
            CallSub2(Main, "ShowBitmap", LoadBitmap(File.DirInternalCache & "/Nuked", line)) <----------------- E R R O R
         End If
      Else
         '   always check that the Cursor returned from the DownloadManager Query method is not empty
         Log("The DownloadManager has no trace of our request, it could have been cancelled by the user using the Android Downloads app or an unknown error has occurred.")
      End If
      
      StatusCursor.Close
      StopService("")
   End If
End Sub

I'm in line 40 an error because it can not find the imgane in the variable "line".


Seek to see that match.
 
Last edited:

mohsen nasrabady

Active Member
Licensed User
Longtime User
in the first post there is a example
remember to add the text mentioned in monifest

the "0" in the download method is the byte that download start from
u can check ur file size and then use it to start download from that's byte
 

aidymp

Well-Known Member
Licensed User
Longtime User
in the first post there is a example
remember to add the text mentioned in monifest

the "0" in the download method is the byte that download start from
u can check ur file size and then use it to start download from that's byte

Hi, yeah I saw the example, but you say use it as a service? how? do you have a project i can download?
 
Top