06/05/2008

Detect internet connectivity on AIR

Hi all, today I´m going to show one way of detecting internet connectivity from an AIR application.

The only thig you have to do is to use a "URLMonitor" object to start monitoring a URLRequest and listen to the StatusEvent.STATUS event, then you have to check the code in the event and this wil tell you if you have internet access at the moment or not.

I have prepared a very tiny application to show hao it works, code following this lines:

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
creationComplete="initApp()">
<mx:Script>
<![CDATA[
import air.net.URLMonitor;
import mx.controls.Alert;

private function onStatusChange(evt : StatusEvent) : void
{
var internetAvailable : Boolean = false;
// If the service is offline
if (evt.code == "Service.unavailable") {
internetAvailable = false; // Set status variable
}
// Service is online
else
{
internetAvailable = true; // Set status variable
}
Alert.show("Internet access --> " + internetAvailable.toString() );
}

private function initApp() : void
{
var urlRequest : URLRequest = new URLRequest("http://www.google.com");
var urlMonitor : URLMonitor = new URLMonitor(urlRequest);
urlMonitor.addEventListener( StatusEvent.STATUS, onStatusChange );
urlMonitor.start();
}
]]>
</mx:Script>
</mx:WindowedApplication>


I hope it helps :)

No comments:

Post a Comment