使用Adobe Air在iPad上检查网络状态的最简单方法

时间:2012-12-04 04:17:04

标签: actionscript-3 air

我想用Adobe Air检查iPad上的网络状态,此时我正在通过向Google.com发送URLREQUEST进行检查。是否还有其他更好的方法来监控网络状态,并知道是否已断开连接或连接。谢谢你的任何建议。

1 个答案:

答案 0 :(得分:6)

这里的棘手部分我们不会在一些间隔时间内ping。所以我们使用

NativeApplication.nativeApplication.addEventListener(Event.NETWORK_CHANGE, onNetwork_ChangeHandler);

当改变净状态变化时它会触发,因此性能也很好。

因为Ping是非常昂贵的操作。所以在网络改变后调用start()URLMontior然后我们调用stop()。

      package com.abc.net
    {
    import air.net.URLMonitor;
    import flash.desktop.NativeApplication;
    import flash.events.Event;
    import flash.events.EventDispatcher;
    import flash.events.IEventDispatcher;
    import flash.events.StatusEvent;
    import flash.net.URLRequest;

    [Event(name="networkStatusChanged", type="flash.events.Event")]
    public class NetStatusMonitor extends EventDispatcher
    {
        private var urlMonitor:URLMonitor;
        private var url:String;

        public function KBNetStatusMonitor(url:String = 'http://www.adobe.com')
        {
            super();
            this.url = url;
            NativeApplication.nativeApplication.addEventListener(Event.NETWORK_CHANGE, onNetwork_ChangeHandler);
        }

        protected function onNetwork_ChangeHandler(event:Event):void
        {
            start();
        }       

        public function start():void
        {
            urlMonitor = new URLMonitor(new URLRequest(url));
            urlMonitor.addEventListener(StatusEvent.STATUS, onNetStatus_ChangeHandler);

            if(!urlMonitor.running)
                urlMonitor.start();
        }

        public function stop():void
        {
            if(urlMonitor.running)
                urlMonitor.stop();
        }

        private function onNetStatus_ChangeHandler(event:StatusEvent):void
        {
            trace("event code " + event.code);
            trace("event level " + event.level);
            dispatchEvent(new NetStatusEvent(NetStatusEvent.NETWORK_STATUS_CHANGED,urlMonitor.available));
            stop();
        }
    }
}

活动类

package com.abc.net
{
    import flash.events.Event;

    public class NetStatusEvent extends Event
    {
        public static const  NETWORK_STATUS_CHANGED:String = "networkStatusChanged";

        public var status:Boolean;

        public function NetStatusEvent(type:String, status:Boolean, bubbles:Boolean=false, cancelable:Boolean=false)
        {
            super(type, bubbles, cancelable);
            this.status = status;
        }

        override public function clone():Event
        {
            return new NetStatusEvent(type, status, bubbles,cancelable);
        }

    }
}

用法:

var netStatusMonitor:NetStatusMonitor = new NetStatusMonitor();
    netStatusMonitor.addEventListener(NetStatusEvent.NETWORK_STATUS_CHANGED,function(event:NetStatusEvent):void {
           statusCallBack.call(null,event.status);
});

netStatusMonitor.start();