Based on another thread, here is a simple way to check if the device has a valid internet connection and show an appropriate error message.
You will need the HTTP library. Response is a Webresponse object and request is a webrequest object.
Let's say you want to download a file when your application starts:
If there is no response from the server, it will raise an error in your sub. When an error is raised, the execution of the sub stops. To avoid this, you must check if the connection is available by calling another thread.
This way, when CheckConnection is called, it returns the connection status. However nothing will happen if there is no connection. No error message, nothing! Let's fix this by adding a new sub: NoConnection.
Now you get a nice error message if there is no connection. However, to avoid confusing the user if the problem is caused by an invalid URL or server downtime, it is good practice to distinguish the internet connection problems from the server problems.
Voilà!
You will need the HTTP library. Response is a Webresponse object and request is a webrequest object.
Let's say you want to download a file when your application starts:
B4X:
Sub App_Start
DownloadStuff
End Sub
If there is no response from the server, it will raise an error in your sub. When an error is raised, the execution of the sub stops. To avoid this, you must check if the connection is available by calling another thread.
B4X:
Sub App_Start
If CheckConnection=True Then
DownloadStuff
End If
End Sub
Sub CheckConnection(URL)
ErrorLabel(offline)
Request.New1(URL)
Response.New1
Response.Value = Request.GetResponse
Response.Close
Return True
offline:
Return False
End Sub
This way, when CheckConnection is called, it returns the connection status. However nothing will happen if there is no connection. No error message, nothing! Let's fix this by adding a new sub: NoConnection.
B4X:
Sub App_Start
If CheckConnection=True Then
DownloadStuff
End If
End Sub
Sub CheckConnection(URL)
ErrorLabel(offline)
Request.New1(URL)
Response.New1
Response.Value = Request.GetResponse
Response.Close
Return True
offline:
Return False
End Sub
Sub NoConnection
MsgBox("Unable to download application")
End Sub
Now you get a nice error message if there is no connection. However, to avoid confusing the user if the problem is caused by an invalid URL or server downtime, it is good practice to distinguish the internet connection problems from the server problems.
B4X:
Sub NoConnection
If CheckConnection("http://google.com")=True Then
MsgBox("Unable to find a valid data connection.")
Else
MsgBox("Unable to download file. The server might be experiencing difficulties.")
End If
End Sub
Voilà!
Last edited: