Search code examples
javascriptandroidcordovaphonegap

Event listener when connecting to a wifi network


I am building an app with cordova for android. I would like to know if there is any way to add an event listener to notify me when the user connects to a wifi network. For example when he/she is using the phone data and connects to a wifi network, I would like to get notified and the same for when the user changes from wifi to data again.

The only way I can think of doing this is to create a setInterval every X miliseconds and check the network information with the plugin cordova-plugin-network-information. But doing that seems very inefficient, and I would like to get notified immediatly.

So is there any way/plugin to add an event listener when there is a network change?

EDIT: I'm not using ionic, just backbone and jquery.

Thanks!


Solution

  • If you are using Ionic then you can do this:

    // watch network for a connection
    let connectSubscription = this.network.onConnect().subscribe(() => {
      console.log('network connected!');
      // We just got a connection but we need to wait briefly
       // before we determine the connection type. Might need to wait.
      // prior to doing any api requests as well.
      setTimeout(() => {
        if (this.network.type === 'wifi') {
          console.log('we got a wifi connection, woohoo!');
        }
      }, 3000);
    });
    
    // stop connect watch
    connectSubscription.unsubscribe();
    

    (Code from Ionic Native Documentation)

    With Cordova there is a plugin called cordova-plugin-network-information, that you can download from Github

    With that you can write stuff like that:

    document.addEventListener("online", onOnline, false);
    
    function onOnline() {
       if(checkConnection===Connection.WIFI){
          // Code
       }
    }
    
    function checkConnection() {
        var networkState = navigator.connection.type;
    
        var states = {};
        states[Connection.UNKNOWN]  = 'Unknown connection';
        states[Connection.ETHERNET] = 'Ethernet connection';
        states[Connection.WIFI]     = 'WiFi connection';
        states[Connection.CELL_2G]  = 'Cell 2G connection';
        states[Connection.CELL_3G]  = 'Cell 3G connection';
        states[Connection.CELL_4G]  = 'Cell 4G connection';
        states[Connection.CELL]     = 'Cell generic connection';
        states[Connection.NONE]     = 'No network connection';
    
        console.log("Connection: "+states[networkState])
    
        return networkState
    }
    

    I have not tested the Cordova example tho