Android Question Check if a file has already downloaded

kozbot

Member
Licensed User
Longtime User
Hi all,

I just wanna check if there is a way that I can use Download manager to check first if a file has been downloaded, and if it is, then open the already downloaded one, but if not, then go ahead and download the file. Here's my code:

B4X:
Sub Button2_Click
    DOWNLOAD_ADDRESS = "http://www.k2m.com.au/UserManual/D8_installer_rev4.7.pdf"
       DOWNLOAD_FILENAME = "D16InstallerGuide.pdf"
    Dim DownloadManagerRequest1 As DownloadManagerRequest
       DownloadManagerRequest1.Initialize(DOWNLOAD_ADDRESS)
       DownloadManagerRequest1.Description="D16 Installer"
       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)
   If DownloadId=DownloadId1 Then
      Dim DownloadManagerQuery1 As DownloadManagerQuery
      DownloadManagerQuery1.Initialize
      DownloadManagerQuery1.SetFilterById(DownloadId)
     
      Dim StatusCursor As Cursor
      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
            Dim intent1 As Intent
            intent1.Initialize(intent1.ACTION_VIEW, "file://"&File.Combine(File.DirRootExternal, DOWNLOAD_FILENAME))
            intent1.SetType("application/pdf")
            intent1.WrapAsIntentChooser("Choose PDF Viewer")
            StartActivity(intent1)
         End If
        
      Else
         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

Thanks in advance!
 

DonManfred

Expert
Licensed User
Longtime User
if file.exists(....) then
do the work for a file already downloaded...
else
do the download
end if
 
Upvote 0

kozbot

Member
Licensed User
Longtime User
Thanks heaps... I don't know why I didn't think of if file.exists...

Thanks for the help!
 
Upvote 0
Top