Exploring the Connection API

When working on a mobile app it's important to know the status of the Internet connection. Using the PhoneGap APIs, you can handle this aspect easily; in fact there are two specific events and an object that allows you to get all the possible information. Once the deviceready event has been fired you can register a listener for the online event and another one for the offline event.

document.addEventListener("online", onDeviceOnline);document.addEventListener("offline", onDeviceOffline);

In the onDeviceOnline handler, you can easily access the connection object stored in the navigator.connection property and access the device's cellular and Wi-Fi connection information using the type property. The possible values stored in the type property are:

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

In order to allow the app to access the connection.type information, you have to add an XML node to the app/res/xml/config.xml Android configuration file.

<plugin name="NetworkStatus" value="org.apache.cordova.NetworkManager" />

You also have to explicitly set up the permissions in the app/AndroidManifest.xml file.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

In order to allow the app to access the connection information on iOS, it is enough to add the following XML node to the config.xml file:

<plugin name="NetworkStatus" value="CDVConnection" />

Pop quiz – getting started with mobile apps

Q.1. How do you handle retina displays in PhoneGap?

  1. It's not possible at all.
  2. With the cordova-cli utility.
  3. Using CSS sprites and creating a 2x image file.

Q.2. In a PhoneGap app the deviceready event is fired when?

  1. After the load event.
  2. When the battery is fully charged.
  3. It's never fired.

Have a go hero – create a network detection utility

Review the information provided in order to add the API and what you learned about AMD JavaScript; create a Require.js module able to detect the network status and to dispatch the information to other modules.

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

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