Android Code Snippet check internet connection

I made some modification to be work fine even if you are connected to network but no internet ..
B4X:
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
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Don't use Phone.Shell. Only Phone.ShellAsync.

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

rscheel

Well-Known Member
Licensed User
Longtime User
This works well for me, I have some extra extras in my code.

B4X:
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
 
Top