【问题标题】:Checking Network Connection on Phonegap检查 Phonegap 上的网络连接
【发布时间】:2016-02-09 23:53:10
【问题描述】:

我是 Javascript 新手和 PhoneGap 新手...

我知道这个问题已经以多种方式发布,但我无法在这里获得基本知识。我试图复制其他答案,但我似乎无法使用 Network-Information 插件: https://github.com/apache/cordova-plugin-network-information

在这一点上,我真的只想要一个在启动时检查网络连接的准系统示例 (onDeviceReady),然后再次检查用户的设备是否已从在线变为离线,反之亦然(看过一些人们建议为这件作品使用 setTimeout)。

经过一些测试,我的 navigator.connection.type 检查似乎没有触发。

我已经安装了 org.apache.cordova.network-inforamtion。请帮忙...我花了大约一个星期的时间把头发拉出来。 :)

我的代码:

<script type="text/javascript" src="js/ga.js">

        // Wait for Cordova to load
        // 
        document.addEventListener("deviceready", onDeviceReady, false);

        // Cordova is loaded and it is now safe to make calls Cordova methods
        //
        function onDeviceReady() {
            checkConnection();
        }

        function checkConnection() {
            var networkState = navigator.connection.type;

            var states = {};
            states[Connection.UNKNOWN]  = 'Unknown connection';
            states[Connection.ETHERNET] = 'Ethernet connection';
            states[Connection.WIFI]     = 'WiFi connection';
            states[Connection.CELL_2G]  = 'Cell 2G connection';
            states[Connection.CELL_3G]  = 'Cell 3G connection';
            states[Connection.CELL_4G]  = 'Cell 4G connection';
            states[Connection.NONE]     = 'No network connection';

            alert('Connection type: ' + states[networkState]);
        }

        document.addEventListener("offline", onOffline, false);

        function onOffline() {
            // Handle the offline event
            alert('Offline');
        }

        document.addEventListener("online", onOnline, false);

        function onOnline() {
            // Handle the online event
            alert('Online');
        }


    </script>

【问题讨论】:

    标签: javascript cordova phonegap-plugins


    【解决方案1】:
    Install network plugin org.apache.cordova.network-information and try the following:-
    
    document.addEventListener("resume", getintoForeground, false);  
    
    function getintoForeground(){
    var ntwk = CheckConnection();
    
    if (ntwk) {
        alert("Network available");
    }else{
        alert("Network  not available");
    }
    }
    
    function CheckConnection(){
        if( !navigator.network ){
                    navigator.network = window.top.navigator.network;
        }
        return ( (navigator.network.connection.type === "none" || navigator.network.connection.type === null || 
                    navigator.network.connection.type === "unknown" ) ? false : true );
        }
    

    【讨论】:

      猜你喜欢
      • 2014-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多