Android Code Snippet Check Internet Connection

Hi
Use below code for check internet connection
The 8.8.8.8 ip is special for ping and Google is owner this IP
This IP is use DNS cache for speed up ping
And never will this address stop

B4X:
Sub ping
    Dim status As Boolean
    status    =    Ping("8.8.8.8","Report",1,4)
End Sub

Sub Ping(Url As String, ResultsType As String, Attempts As Int, Timeout As Int) As Boolean

    Dim sb As StringBuilder
    Dim p As Phone
    Dim Option As String
    
    sb.Initialize

    If ResultsType = "Report" Then    Option = " -v "
    If ResultsType = "Summary" Or ResultsType = "Status" Then Option = " -q "

    p.Shell("ping -c " & Attempts & " -W " & Timeout & Option & Url, Null, sb, Null)

    If sb.Length = 0 Or sb.ToString.Contains("Unreachable") Then
        Return False
    End If
    
    Return True

End Sub
 

MarcoRome

Expert
Licensed User
Longtime User
You can easily manage the internet connection both wifi and 3-4G. With the following code when there is no internet an activity will be opened (see video). As soon as the internet is available ( check every 5 sec ), the previous activity will also be back online




B4X:
'Management Connection 
    Dim j As HttpJob
    j.Initialize("", Me)
    j.GetRequest.Timeout = 2000
    j.Download("https://www.google.com")
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        CallSub(act_check_internet, "chiudi")
    Else
        StartActivity(act_check_internet)
        Return
    End If
    j.Release

Code, activity in foreground until no connection:

B4X:
#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim check_rete As Timer

End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("lay_check_internet")
    
    check_rete.Initialize("check_rete", 5000)
    check_rete.Enabled = True

End Sub

Sub check_rete_Tick
    'Controllo se esiste la rete
    Dim j As HttpJob
    j.Initialize("", Me)
    j.GetRequest.Timeout = 2000
    j.Download("https://www.google.com")
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        check_rete.Enabled = False
        Activity.Finish
    End If
    j.Release
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub chiudi
    Activity.Finish
End Sub


Sub Activity_KeyPress(KeyCode As Int) As Boolean

    'No Close 
    If KeyCode = KeyCodes.KEYCODE_BACK Then
        Return True
    End If
    
End Sub
 

LucaMs

Expert
Licensed User
Longtime User
I remember that pinging is not reliable (not for unreachable or "unresponsive" IP addresses). You can find more than one post about this on this site.

The only solution, often suggested by Erel, is to download a "light" page (with a few graphic objects); better two different pages, because the first could be offline for various reasons (it can happen even to the big Google). This is what @MarcoRome has suggested, in a very not self-centered manner :D
 

MarcoRome

Expert
Licensed User
Longtime User
I remember that pinging is not reliable (not for unreachable or "unresponsive" IP addresses). You can find more than one post about this on this site.

The only solution, often suggested by Erel, is to download a "light" page (with a few graphic objects); better two different pages, because the first could be offline for various reasons (it can happen even to the big Google). This is what @MarcoRome has suggested, in a very not self-centered manner :D

https://etherealmind.com/what-is-the-best-ip-address-to-ping-to-test-my-internet-connection/

https://whatsabyte.com/internet/best-public-dns-servers/
 

Pooya1

Active Member
Licensed User
You can easily manage the internet connection both wifi and 3-4G. With the following code when there is no internet an activity will be opened (see video). As soon as the internet is available ( check every 5 sec ), the previous activity will also be back online




B4X:
'Management Connection
    Dim j As HttpJob
    j.Initialize("", Me)
    j.GetRequest.Timeout = 2000
    j.Download("https://www.google.com")
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        CallSub(act_check_internet, "chiudi")
    Else
        StartActivity(act_check_internet)
        Return
    End If
    j.Release

Code, activity in foreground until no connection:

B4X:
#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim check_rete As Timer

End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("lay_check_internet")
   
    check_rete.Initialize("check_rete", 5000)
    check_rete.Enabled = True

End Sub

Sub check_rete_Tick
    'Controllo se esiste la rete
    Dim j As HttpJob
    j.Initialize("", Me)
    j.GetRequest.Timeout = 2000
    j.Download("https://www.google.com")
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        check_rete.Enabled = False
        Activity.Finish
    End If
    j.Release
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub chiudi
    Activity.Finish
End Sub


Sub Activity_KeyPress(KeyCode As Int) As Boolean

    'No Close
    If KeyCode = KeyCodes.KEYCODE_BACK Then
        Return True
    End If
   
End Sub
Yes i know that your code is good but when i download google page,actually download 50kb files only for test
Is it good for user?
 

LucaMs

Expert
Licensed User
Longtime User
This ISNT ping is a standard http request
I know; I have to explain my previous post in Italian :)

Dicevo che il ping non è affidabile, che è meglio effettuare il download di un paio di pagine, come ha sempre suggerito Erel e come hai fatto tu.
Solo che ho aggiunto un commento scherzoso sul metodo in cui hai suggerito di scaricare google.com... per niente egocentrico (era una battuta, Marcooo :))
 

MarcoRome

Expert
Licensed User
Longtime User
I know; I have to explain my previous post in Italian :)

Dicevo che il ping non è affidabile, che è meglio effettuare il download di un paio di pagine, come ha sempre suggerito Erel e come hai fatto tu.
Solo che ho aggiunto un commento scherzoso sul metodo in cui hai suggerito di scaricare google.com... per niente egocentrico (era una battuta, Marcooo :))

Ah Lu... ti giuro che non l'avevo capito :D:D
 

aeric

Expert
Licensed User
Longtime User
Similar to @MarcoRome suggestion, I will normally put a simple php file in my hosting server to return a json response and by using httputils we can check the response success or not. Normally the error is like connection timed out or unreachable host then we can show to user Internet is not connected or unable to connect to server.
 

Tadeu Botelho

Member
Licensed User
Longtime User
Similar to @MarcoRome suggestion, I will normally put a simple php file in my hosting server to return a json response and by using httputils we can check the response success or not. Normally the error is like connection timed out or unreachable host then we can show to user Internet is not connected or unable to connect to server.

This solution is very good. Via JSON we can receive a single return string from the programmer's own server.
For example:
Return String "0" means internet OFF.
Return String "1" means internet ON.
In order to consume less data during the checks.
Meanwhile, heavy checks can be made through the backend of the server that will be running on an unlimited data plan and much faster than the user's cellular device.
 

Pooya1

Active Member
Licensed User
This solution is very good. Via JSON we can receive a single return string from the programmer's own server.
For example:
Return String "0" means internet OFF.
Return String "1" means internet ON.
In order to consume less data during the checks.
Meanwhile, heavy checks can be made through the backend of the server that will be running on an unlimited data plan and much faster than the user's cellular device.
You suppose you have 100k users
Every 5 second you send request to server and get it for check connection
100000 * 5 = 500000
You send 500000 request for server every 5 seconds
It is bad solution
Tough file is 1byte but actually you send Http request to server and it is pressure for server
 

MarcoRome

Expert
Licensed User
Longtime User
You suppose you have 100k users
Every 5 second you send request to server and get it for check connection
100000 * 5 = 500000
You send 500000 request for server every 5 seconds
It is bad solution
Tough file is 1byte but actually you send Http request to server and it is pressure for server
First you have this call with google server. I dont think thst have problem big g.
Next... Found another solution
 
Last edited:

Pooya1

Active Member
Licensed User
First you have this call with google server. I dont think thst have problem big g.
Next... Found another solution
After search in Google,i get two result about check connection
If my app is Chat application,after to connect server,we can check internet connection
If not so
Ping is best solution
Google has provided us with IP 8.8.8.8 for special ping and because this ip use Cache DNS so it is OK always
 

LucaMs

Expert
Licensed User
Longtime User
[stackoverflow.com]


upload_2018-7-23_11-18-22.png
 
Top