2

我想用 Adob​​e Air 检查 iPad 上的网络状态,此时我正在通过向 Google.com 发送 URLREQUEST 来检查。有没有其他更好的方法来监控网络状态,并知道是否有连接或连接已被丢弃。感谢您的任何建议。

4

1 回答 1

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();
于 2012-12-04T05:06:00.530 回答