Easy Code Share > Cordova > How to Detect Cordova Wifi Connection

How to Detect Cordova Wifi Connection


You can detect Cordova Wifi and Cellular network connections in two ways: repeating checks and event notification. However, for more efficient result, we introduce a Plugin based on Network Information API to monitor network connection by event notification. At end of the post, we will build a Cordova APP by using Cordova CLI commands.

All codes here are not complicated, so you can easily understand even though you are still students in school. To benefit your learning, we will provide you download link to a zip file thus you can get all source codes for future usage.

Estimated reading time: 6 minutes

 

 

BONUS
Source Code Download

We have released it under the MIT license, so feel free to use it in your own project or your school homework.

 

Download Guideline

  • Prepare HTTP server such as XAMPP or WAMP in your windows environment.
  • Download and unzip into a folder that http server can access.
 DOWNLOAD SOURCE

 

SECTION 1
Cordova Detect Wifi

The Cordova Plugin to detect Wifi is designed upon Network Information API. In fact, it provides connection types and event-driven methods to help developers know how network state changes.

 

Network Information API

W3C Network Information API is the basics for Cordova Network Information Plugin, which provides sensitive events for developers to detect Wifi and Cellular connections, and therefore handle exceptions.

Although there are more than one property in Network Information API, Cordova Network Information Plugin use only the property of navigator.connection.type so far. Formally, possible constants of connection type are

  • Connection.UNKNOWN
  • Connection.ETHERNET
  • Connection.WIFI
  • Connection.CELL_2G
  • Connection.CELL_3G
  • Connection.CELL_4G
  • Connection.CELL
  • Connection.NONE

However, we find that only constant wifi, 4g and none are available to appear in this Cordova Plugin. Where none means network is disconnected. Should we periodically check if connection type is changed like the way done in How MQTT Plus Cordova GPS APP Track My Family? Of course not, the Plugin will raise events to trigger your callback functions.

 

Event Notification

Truly, two sensitive events online and offline let you know whether there is any connection established, and check if all connections are down.

document.addEventListener('online', checkConnection, false);
document.addEventListener('offline', checkConnection, false);

Where checkConnection() stands for callback functions.

 

SECTION 2
Wifi vs Cell

The example demonstrates how Cordova Plugin detect Wifi and 4G. In addition, debugging process shows network state transition. At last, we build a Cordova APP by a brief procedure.

 

Default to Wifi

Mobile phone always set Wifi as default. That is, if both Wifi and 4G connections exist, use Wifi connection. This panel layout is in Wifi connection.

Wifi Default Connection

Let look at debug logs by using Android Studio as below. Blue square contains messages for the case that Wifi is on.

Cordova Detect Wifi and 4G

At this time, if 4G connection becomes up, the network state in panel get not changed because this phone had already connected to internet in Wifi.

Next, if Wifi goes down, network state will temporarily switch to none, and then to 4g. The debugging logs in green square are for disconnection, while those in orange square are for 4G connection.

None Lose Connection

4G Cellular Connection

 

The Example

The screen layout leverages jQuery Mobile Pages to fit mobile phones completely for Cordova APPs. If not using it, it more difficult to make APPs responsive.

index.html
<div data-role="page" style="background:gray;">
    <div data-role="header">
        <h1>NETWORK INFO</h1>
    </div>
    <div data-role="content">
        <table>
        <tr><th>Network</td> <th>Status</td></tr>
        <tr><td>Status</td> <td id="status">⦿</td></tr>
        <tr><td>Type</td> <td id="type"></td></tr>
        </table>
    </div>
    <div data-role="footer" data-position="fixed">
        <p style="text-align:center;">Cordova Network Information Plugin</p>
    </div>
</div>

We add online and offline event listeners to detect Cordova Wifi when device is ready. Along with callback functions related to the events, developers can handle exceptions or resume pending jobs. wifi, 4g and none are three possible connection types driving whole network state transition.

index.js
function onDeviceReady() {
    // Cordova is now initialized. Have fun!
    console.log('Running cordova-' + cordova.platformId + '@' + cordova.version);
    checkConnection();
    document.addEventListener('online', checkConnection, false);
    document.addEventListener('offline', checkConnection, false);
}
function checkConnection() {
    var netstatus = navigator.connection.type;
    console.log('*** conn type: ' + netstatus);
    on_color = "lightgreen";
    off_color = "white";
    if(netstatus == "none") {
        $('td#status').css("color", off_color);
    } else {
        $('td#status').css("color", on_color);
    }
    $('td#type').html(netstatus);
}

 

Build a Cordova APP

Commonly, developers use Cordova CLI command lines to build an APP project. Before building process, you should at least determine three arguments for a Cordova project.

  • PATH: detectwifi
  • ID: com.easycodeshare.detectwifi
  • NAME(human readable): DetectWifi
c:\>cordova create detectwifi com.easycodeshare.detectwifi DetectWifi
c:\>cd detectwifi
c:\detectwifi>cordova platform add android
c:\detectwifi>cordova plugin add cordova-plugin-network-information

Once the project is created, replace content of the folder detectwifi/www with all downloaded source codes. Subsequently, add the Platform Android and the Plugin Network Informatoin using the command lines above.

index.html
<link rel="stylesheet" href="css/1.4.5/jquery.mobile.min.css">
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/1.4.5/jquery.mobile.min.js"></script>

As above, jQuery and jQuery Mobile files should be downloaded in advance, rather than be referenced using CDN. Check whether there is any CDN included if you have made any change on our source codes. The issue about not using CDN can be found in 3 Steps Cordova Build APPs from jQuery Mobile.

Finally, let’s build an Cordova APP using one command line.

c:\detectwifi>cordova build android
Checking Java JDK and Android SDK versions
ANDROID_SDK_ROOT=undefined (recommended setting)
ANDROID_HOME=undefined (DEPRECATED)
Using Android SDK: C:\Users\user\AppData\Local\Android\sdk
Subproject Path: CordovaLib
Subproject Path: app
Starting a Gradle Daemon (subsequent builds will be faster)
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.5/userguide/command_line_interface.html#sec:command_line_warnings
BUILD SUCCESSFUL in 29s
40 actionable tasks: 40 up-to-date
Built the following apk(s):
        c:\detectwifi\platforms\android\app\build\outputs\apk\debug\app-debug.apk

 

FINAL
Conclusion

For the purpose of demonstration of mobile network state transition, we simulate a panel in a way that mobile phones indicate what kinds of network connection is currently used.

Thank you for reading, and we have suggested more helpful articles here. If you want to share anything, please feel free to comment below. Good luck and happy coding!

 

Learning Tips

Let us suggest a excellent way to learn HTML scripts here. Using Google Chrome F12 Inspect or Inspect Element will help you study the codes.

In Google Chrome, there are two ways to inspect a web page using the browser built-in Chrome DevTools:

  • Right-click an element on the page or in a blank area, then select Inspect.
  • Go to the Chrome menu, then select More Tools > Developer Tools.

 

Suggested Reading

Leave a Comment