1. Black Friday Sale - 50% off

    B4A Standard for $29 instead of $59!
    Buy Now
    Dismiss Notice

Checking the internet connection

Discussion in 'Code Samples & Tips' started by N1c0_ds, Jan 2, 2009.

  1. N1c0_ds

    N1c0_ds Active Member Licensed User

    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:

    Code:
    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.

    Code:
    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.
    Code:
    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.

    Code:
    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: Jan 2, 2009
  2. Erel

    Erel Administrator Staff Member Licensed User

    Thank you for sharing this important tip :)
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice