Check Internet connection

Status
Not open for further replies.

robife

Member
Licensed User
Longtime User
Hi guys
I need help to check internet connection is ON or OFF

I try eks.
B4X:
    If CheckConnection Then
           Msgbox("You connected internet", "OK")
    Else
           Msgbox("You didn't connect internet", "Error")
    End If


Sub CheckConnection As Boolean
    Dim p As Phone
    
    If (p.GetDataState == "CONNECTED") Then
        Return True
    End If
        
    If (p.GetSettings ("wifi_on") == 1) Then
        Return True
    End If
    
    If (p.GetDataState == "DISCONNECTED") Then
        Return False
    End If
    
    If (p.GetDataState == "SUSPENDED") Then
        Return False
    End If
End Sub


But how to do it on application with label text ?

or Only to show msg when Internt is OFF, not each time we start app
 

NeoTechni

Well-Known Member
Licensed User
Longtime User
I prefer to check ServerSocket.GetMyIp and test whether it is "127.0.0.1" (not connected to any network) or any other IP address (connected to a network).

I was using that for ages and it worked fine, but all of a sudden it stopped working.

I am getting an IP address of 25.25.36.106 with airplane mode on.
Chrome tells me mobile data and wifi is off.

And that IP shows as a UK, Ministry of Defense IP address....
http://myip.ms/view/ip_addresses/421078016/25.25.36.0_25.25.36.255
 
Last edited:
Upvote 0

NeoTechni

Well-Known Member
Licensed User
Longtime User
B4X:
Sub IsConnected As Boolean 
   Dim P As Phone,server As ServerSocket'Add a reference to the network library  'Check status: DISCONNECTED 0
   Try
       server.Initialize(0, "")
      Log("mobile data state: " & P.GetDataState & " wifi_on: " & P.GetSettings("wifi_on") & " server ip: " & server.GetMyIP & CRLF &  "wifi ip: " & server.GetMyWifiIP)
       If server.GetMyIP = "127.0.0.1" Then Return False  'this is the local host address
      If Not(P.GetDataState.EqualsIgnoreCase("CONNECTED")) AND server.GetMyWifiIP = "127.0.0.1" Then Return False
       Return True
   Catch
      Return False
   End Try
End Sub

I've had to alter the code to this... I don't understand how it stopped working. code to check if Wifi is on also stopped working recently

I used to use
B4X:
Sub isWIFI_enabled As Boolean 
   Dim P As Phone '0 is off, 2 is on, don't know if it's connected, same for 3
   Return P.GetSettings ("wifi_on") =1
End Sub

But now it can be 2 or 3 and still have wifi on...
 
Upvote 0

NeoTechni

Well-Known Member
Licensed User
Longtime User
You can try to download a page such as google.com. This is eventually the best way to test for an internet connection as the device might be connected to a local network without an internet connection.

That would waste a lot of bandwidth over time.
 
Upvote 0

Harris

Expert
Licensed User
Longtime User
B4X:
Public Sub ExecuteBatch(ListOfCommands As List, Tag As Object)
    If IsConnected = False Then
      ToastMessageShow(" No Internet Connection",False)
      Return
    Else
      ToastMessageShow(" Connecting - Sending Data",False)
    End If   
    Dim j As HttpJob
    Dim ms As OutputStream
    Dim out2 As OutputStream = StartJob(j,ms, Tag)
    WriteInt( ListOfCommands.Size, out2)
    For Each Command As DBCommand In ListOfCommands
        WriteObject( Command.Name, out2)
        WriteList(Command.Parameters, out2)
    Next
    out2.Close
    j.PostBytes(link & "?method=batch", ms.ToBytesArray)
End Sub

I tried Neo's code above. Works to a degree.

If I have a wifi connection, it returns true - even with no internet connection.

My problem is that I start an activity and send a record to my server (RDC). This activity should remain active until the DONE button is pressed. If no internet connection, the jobdone terminates (or rather suspends) the current activity and returns to the main activity (where jobdone sub resides). Pressing back button will reveal the desired activity.

Can I attempt to "ping" my server to see if I have internet - as Erel suggested (and how to ping as opposed to download a page)? Or something else?

Thanks
 
Upvote 0

warwound

Expert
Licensed User
Longtime User
Upvote 0

appie21

Active Member
Licensed User
Longtime User
Is it also posible to get the type of internet conection. i mean connected to a 2G, 3g or 4G Network?
 
Upvote 0

wonder

Expert
Licensed User
Longtime User
I'm confused.

So what's the fastest, most reliable and definitive method?
 
Upvote 0

Peter Simpson

Expert
Licensed User
Longtime User
I used to use the 127.0.0.1 method @wonder but lately I've switched to using the MLWiFi library as that allows me to test for all internet full stop, or just WiFi internet.

I still use the 127.0.0.1 in some apps, but these days I personally prefer using MLWiFi to test if there's an internet connection.
 
Upvote 0

JoanRPM

Active Member
Licensed User
Longtime User
Try this:

B4X:
Sub Globals
    Dim job As HttpJob
    Dim ConnexioInternet As Boolean
End Sub

Sub Activity_Create(FirstTime As Boolean)
    job.Initialize("Job1", Me)
    job.Download("http://www.google.com")
End Sub

Sub JobDone(job As HttpJob)
    If job.JobName="Job1" AND job.Success=False Then
        ConnexioInternet = False
    Else
        ConnexioInternet = True
    End If
    job.Release
End Sub

It works for me.

Regards.
 
Upvote 0

sorex

Expert
Licensed User
Longtime User
depending on the app functionality you can combine the download method above with the connectivity change events from the phone. there you can check if the ip is 0.0.0.0 or 127.0.0.1 if not you can send an (ip) update request to the backend.
 
Upvote 0

Derek Johnson

Active Member
Licensed User
Longtime User
I've just tested this simple alternative and it seems to work OK for me:

B4X:
Sub Connected As Boolean
    'Requires Phone Library
    Dim p As Phone
    Dim Response, Error As StringBuilder
    Response.Initialize
    Error.Initialize
    'Ping Google DNS - if you can't reach this you are in serious trouble!
    p.Shell("ping -c 1 8.8.8.8",Null,Response,Error)
    Log("======= Response ========")
    Log(Response)
    Log("======= Error ===========")
    Log(Error)
    Log("======================")

    If Error.ToString="" Then
        Return True
    Else
        Return False
    End If

End Sub

I'm not sure if all devices allow the use of the shell command. It worked on my non-rooted Moto G.
I tested in with Aeroplane mode ON and OFF.

Derek
 
Last edited:
Upvote 0

Derek Johnson

Active Member
Licensed User
Longtime User
Just a footnote to my post above.

Should the user of your app happen to be in China, then the ping to the Google DNS will fail. Not generally a problem though for most apps.

The DNS ping test is very quick, and I use it before trying to access one of a number of websites from my app. It will rule out common forms of connectivity error I.e.Device in Aeroplane mode, No Wifi, not logged in to a Hotspot needing a password.

It is not infallible though and requests for a specific website could still fail for a variety of reasons. Some examples are:

Security Certificate Not Trusted
Page not found

When accessing a webpage as part of my app, I check for a Page Title containing Page Not Found in the URL loaded event and then load an error message. This stops the full error URL from being displayed to the user.
 
Upvote 0
Status
Not open for further replies.
Top