When a device resumes from standby, it can take a while for the radio (WLAN) to establish a connection. If your application requires interaction with a remote server then notification of a valid network connection may be required. This can be achieved using the Network API supplied as part of RhoElements. Here is a quick walk-through example that makes use of the Network API.
In this example we will enable, or disable a button that is used to get some data from the server. When the network is connected the button will be enabled, and when the network is unreachable the button will be greyed out; preventing the user from clicking it.
Register for a network connected/disconnected event.
The %json parameter is a directive to return data as a JSON object.
Setting the callback function
‘onNetworkEvent’ will be called when there is a change to network connectivity. We handle that by calling ‘Update’ with a Boolean result that is true when connected. On receiving the connected parameter, the button is enabled and the polling interval is set to a value that that does not impact our network bandwidth.
Why set the Polling Interval?
The default values for the network API are less than ideal when we require a fast re-connect time.
When we are waiting for network notification it is important to be notified of a connection as soon as one is available. There are two parameters that will affect the notification. The parameters are fairly self explanatory, but warrant some attention.
The network plug-in can be thought of as a network subsystem sampler that takes samples at the rate that you set, and fires an event when the subsystem state changes to connected or disconnected.
After your application receives a disconnection notification it makes sense to reduce the poll interval to check more frequently.
For example; if we were to check for a network connection every 5 seconds, and the network subsystem connects one second after a poll. We would need to wait a further 4 seconds before our application receives notification.
The ‘connectionTimeout’ property is the amount of time the network plug-in will attempt to connect to the specified URL before it gives up and assumes 'disconnected'. This value should be tweaked according to the expected network speed.
Increasing the polling frequency should be applied with caution. It will affect the battery life of your device, and may impede other applications that rely on network bandwidth.
I have attached the full example code (NetworkConnection.zip). Line 117 will need to point to wherever you wish to place the AJAX file. Which in this case is simply a text file containing "Hello World!".