Android Code Snippet check internet connection

Discussion in 'Code Snippets' started by HAH, Nov 10, 2018.

  1. HAH

    HAH Active Member Licensed User

    I made some modification to be work fine even if you are connected to network but no internet ..
    Code:
    Sub Connected As Boolean
        
    'Requires Phone Library
        Dim p As Phone
        
    Dim Response, Error As StringBuilder
        Response.Initialize
        Error.Initialize
        
    'Ping Google DNS 
        p.Shell("ping -c 1 8.8.8.8",Null,Response,Error)
        
        
    If Error.ToString="" And Response.ToString.Contains("Destination Host Unreachable")=False Then
            
    Return True
        
    Else
            
    Return False
        
    End If

    End Sub
    Orginal post here
     
  2. Erel

    Erel Administrator Staff Member Licensed User

    Don't use Phone.Shell. Only Phone.ShellAsync.

    Code:
    Sub CheckConnected As ResumableSub
       
    'Requires Phone Library
       Dim p As Phone
       
    'Ping Google DNS
       Wait For (p.ShellAsync("ping"Array As String("-c""1""8.8.8.8"))) Complete (Success As Boolean, ExitValue As Int, StdOut As String, StdErr As String)
       
    If StdErr = "" And StdOut.Contains("Destination Host Unreachable")=False Then
           
    Return True
       
    Else
           
    Return False
       
    End If
    End Sub
    You need to call it like this:
    Code:
    Wait For (CheckConnected) Complete (Connected As Boolean)
    If Connected Then
     ...
    Running a shell command can take longer than expected in some cases. Doing it synchronously might cause your app to freeze and eventually killed with an ANR.
     
    toby and HAH like this.
  3. rscheel

    rscheel Well-Known Member Licensed User

    This works well for me, I have some extra extras in my code.

    Code:
    Sub CheckConected() As Boolean
        
    Dim j As HttpJob
        j.Initialize(
    "", Me)
        j.GetRequest.Timeout = 
    2000
        j.Download(
    "https://www.google.com"'Example
        Wait For (j) JobDone(j As HttpJob)
        
    If j.Success Then
            
    Log(j.GetString)
            
    Return True
        
    Else
            
    Log("Sin Conexión")
            
    Return False
        
    End If
        j.Release
    End Sub
     
    HAH, ShaneG30 and inakigarm like this.
  4. inakigarm

    inakigarm Well-Known Member Licensed User

    I'm using this code also (changing google to my server IP) to test internet connection to my server
     
    rscheel likes this.
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