14. Connection

The PhoneGap Connection object provides an application with information about the current network connection available to the application. The object exposes a single property, connection.type, as well as the following constants:

Connection.CELL_2G

Connection.CELL_3G

Connection.CELL_4G

Connection.ETHERNET

Connection.NONE

Connection.UNKNOWN

Connection.WIFI

An application will query the connection.type property and compare the results against these constants to determine the specific type of connection available. You’ll see an example of this shortly.

Modern smartphones include multiple radios, so the device can connect to several types of networks throughout the day. The device typically maintains a constant connection to the cellular network whenever possible, which it uses for both voice and data communication. Devices typically connect to Wi-Fi networks as well, primarily for data communication but sometimes for voice communication.

When it comes to data communication, the type of connection a mobile application would use to communicate with server-based resources, the device typically prioritizes its connections and uses the fastest (and least expensive) connection whenever possible. For example, a device will typically place a higher priority on Wi-Fi connections and use cellular connections only when a Wi-Fi connection is not available.

Because of this prioritization, PhoneGap’s connection.type property will return the primary connection type, which is the connection type currently being used for data communication. As the device moves in and out of cellular and Wi-Fi coverage throughout the day, it typically doesn’t lose its network connectivity; the device instead seamlessly transitions between available network types doing its best to keep the connection available.

An application would use the online and offline events (described in Chapter 17) to determine whether connectivity is available but would use connection.type (possibly in conjunction with those events) to determine how robust the connection is. When transferring a small to medium amount of data (ranging from bytes to kilobytes, for example), the network speed is important but not critical. When an application prepares to transmit or receive a large amount of data across the network, though, knowledge of the type of network is critical, and that’s the primary reason connection.type exists.

Before starting a large download or upload, an application might want to check to see whether the device has a high-speed (Wi-Fi or 4G) connection and defer the transmission unless a high-speed connection is available.

var networkState = navigator.network.connection.type;
if (networkState == Connection.NONE) {
  //No network available, so tell the user
  //and defer the update
}

The PhoneGap API documentation provides a simple example of how you can use the connection object to detect the current network type and display an alert to the user. Unfortunately, that’s not an example that can really be used in a production application. I thought I’d tweak it a bit to make it more useful. Take a look at the following code:

var states = {};
states[Connection.UNKNOWN] = 'Unknown';
states[Connection.ETHERNET] = 'Ethernet';
states[Connection.WIFI] = 'Wi-Fi';
states[Connection.CELL_2G] = 'Cell 2G';
states[Connection.CELL_3G] = 'Cell 3G';
states[Connection.CELL_4G] = 'Cell 4G';
states[Connection.NONE] = 'No network';

function getConnectionTypeStr() {
  //get the network state
  var networkState = navigator.network.connection.type;
  //return a string representing the current network state
  return states[networkState];
}

In this example, I pulled the population of the states object out of the function and instead execute that code within the script directly so it executes only once. Next I updated the function so it returns a string representing the network type, so an application could, for example, update its UI with the current network type if appropriate for the application.

Example 14-1 shows the function put to use in an application. It’s the same application used to demonstrate the use of the Event API’s online and offline events (described in Chapter 17). In this example, the application’s main page gets updated with the network connection type every time the device goes online.


Example 14-1

<!DOCTYPE html>
<html>
  <head>
    <title>Example 14-1</title>
    <meta http-equiv="Content-type" content="text/html;
      charset=utf-8">
    <meta name="viewport" id="viewport"
      content="width=device-width, height=device-height,
      initial-scale=1.0, maximum-scale=1.0, user-scalable=no;"
    />
    <script type="text/javascript" charset="utf-8"
      src="jquery.js"></script>
    <script type="text/javascript" charset="utf-8"
      src="phonegap.js"></script>
    <script type="text/javascript" charset="utf-8">

      //build an accessible representation of the different
      //network state values
      var states = {};
      states[Connection.UNKNOWN] = 'Unknown';
      states[Connection.ETHERNET] = 'Ethernet';
      states[Connection.WIFI] = 'Wi-Fi';
      states[Connection.CELL_2G] = 'Cell 2G';
      states[Connection.CELL_3G] = 'Cell 3G';
      states[Connection.CELL_4G] = 'Cell 4G';
      states[Connection.NONE] = 'No network';

      function onBodyLoad() {
        document.addEventListener("deviceready", onDeviceReady,
          false);
      }

      function onDeviceReady() {
        navigator.notification.alert("PhoneGap is ready!");
        //Add the online event listener
        document.addEventListener("online", isOnline, false);
        //Add the offline event listener
        document.addEventListener("offline", isOffline, false);
      }
  
      function isOnline() {
        var d = new Date();
        $('#networkInfo').prepend("Online (" +
          getConnectionTypeStr() + ")<br />");
      }
    
      function isOffline() {
        var d = new Date();
        $('#networkInfo').prepend("Offline<br />");
      }
    
      function getConnectionTypeStr() {
        //get the network state
        var networkState = navigator.network.connection.type;
        //return a string representing the current network state
        return states[networkState];
      }
    </script>
  </head>
  <body onload="onBodyLoad()">
    <h1>Example 14-1</h1>
    <p id="networkInfo"></p>
  </body>
  </body>
</html>


Figure 14-1 shows the application running on an Android device.

Image

Figure 14-1 Example 14-1 running on an Android device

The application appends the current network status to the top of the list, so what you see in the figure is activity over time with the most recent event at the top. The application uses the jQuery $().prepend method to accomplish this. As you can see from the example, with the cellular and Wi-Fi radios on, the connection defaults to the Wi-Fi network. When I turned the radio off (third line from the top), the device fired the offline event first (even though the cellular connection was still available); then it fired the online event when it transferred to the cellular connection (the top line).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset