There are many ways this could be done. My preference would be to combine the server test and the file transfer into a single subroutine. I tried this out. It is easier to use B4J for testing so I wrote a class. You should be able to use this directly in B4A but you might prefer to adapt the scheme, or choose some other path. Note that I am using a different port number than you used in your post above. Here is the class ...
[CODE lang="b4x" title="FTPLink Class"]Sub Class_Globals
Private xui As XUI
Private FTP As FTP
Private dummyfile As String = "dummy.txt" ' Used to test server link
Private host As String ' Server location
Private user As String ' Account name
Private pword As String ' Password
Private client As Object ' Caller activity
Private handler As String ' Callback event handler
End Sub
Public Sub Initialize(hostname As String, username As String, password As String, caller As Object, eventHandler As String)
host = hostname
user = username
pword = password
client = caller
handler = eventHandler
If xui.IsB4J Then ' NOTE : Only needed if running on PC
xui.SetDataFolder("Put appname here")
End If
End Sub
' Download a file from FTP host after testing for active link
Public Sub getFile(hostfolder As String, filename As String)
If Not(hostfolder.EndsWith("/")) Then hostfolder = hostfolder & "/"
If Not(File.Exists(xui.DefaultFolder, dummyfile)) Then ' Use short file to test for server
File.WriteString(xui.DefaultFolder, dummyfile, "Test data")
End If
FTP.Initialize("FTP", host, 21, user, pword)
FTP.PassiveMode = True
FTP.TimeoutMs = 200 ' Set timeout at lower limit
Dim sf As Object ' Issue job to upload test file
sf = FTP.uploadFile(xui.DefaultFolder & "\", dummyfile, True, hostfolder & dummyfile)
Wait For (sf) FTP_uploadCompleted (ServerPath As String, Success As Boolean)
If Not(Success) Then
FTP.Close
CallSub2(client, handler, "Host not available")
Return
End If
FTP.TimeoutMs = 5000 ' Server test succeeded : increase timeout
sf = FTP.DownloadFile(hostfolder & filename, False, xui.DefaultFolder & "/", filename)
Wait For (sf) FTP_DownloadCompleted (ServerPath As String, Success As Boolean)
Dim msg As String
If Success Then msg = "Transfer complete" Else msg = "Transfer failed"
CallSub2(client, handler, msg) ' Pass result to callback handler
FTP.Close
End Sub[/CODE]
Here is the code in the calling activity ...
B4X:
. . .
Private FTPLink As FTPLink
. . .
FTPLink.Initialize("Server_name, "User_name", "Password", Me, "FTPstatus") ' Define server and callback handler
. . .
Private Sub btnTest_Click
FTPLink.getFile("server folder name", "filename")
End Sub
Public Sub FTPstatus(Msg As String)
Log("FTP : " & Msg)
End Sub
I tested for "server offline" by setting the FTP timeout to 20msec as I could not make my usual server inactive.