DEV Community

Cover image for Checking Internet Status in Basic4Android
Ali Karbasi
Ali Karbasi

Posted on • Updated on

Checking Internet Status in Basic4Android

Basic4Android lets you use WebView to load URLs in your application, but if your phone isn’t connected to the internet when the program runs, an error message will show up in the WebView itself, which doesn’t look nice…

By using this piece of code, you can check if the user’s phone is connected to the internet or not. Depending on the information you get, you can either hide the WebView or display an error message. Of course, this code can have other applications as well, but in this post and video (which will be released soon), I’m using it for this purpose.

Required libraries:

Network
Enter fullscreen mode Exit fullscreen mode

First you need to define a ServerSocket variable in Process_Globals:

Sub Process_Globals

    Dim server As ServerSocket

End Sub
Enter fullscreen mode Exit fullscreen mode

Then, check the phone’s IP address using the following Sub:

Sub GetIp As Boolean

    server.Initialize(0,"")

    If server.GetMyIP = "127.0.0.1" Then
      Return False
    Else
      Return True
    End If

End Sub
Enter fullscreen mode Exit fullscreen mode

As you know, if we’re not connected to the internet, the default IP address of the device is 127.0.0.1. The If condition checks this IP and returns False if the phone’s IP matches 127.0.0.1 and if the IP address is not 127.0.0.1 (meaning we are connected to the internet), it returns True.

By the way, the number 0 in server.Initialize(0,"") represents the port number. 😅 (More Info…)

Last but not least, you can use the True or False value to check if the internet connection is working:

If GetIp=True Then
  ToastMessageShow("Internet connection is established.", False)
Else
  ToastMessageShow("No internet connection!", False)
End If
Enter fullscreen mode Exit fullscreen mode

That’s all!

Happy coding :D

Top comments (1)

The discussion has been locked. New comments can't be added.
Collapse
 
Sloan, the sloth mascot
Comment deleted