检查phonegap中的网络状态?

时间:2012-11-08 06:49:31

标签: android cordova phonegap-plugins

我正在使用phonegap开发应用程序。在我的应用程序中,我需要检查网络状态。我使用了以下代码,

   function checkConnection() 
{
    var networkState            = navigator.network.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';

    console.log("network------"+networkState);               

    return networkState;             
}

它工作正常,但离线模式也是返回3g(在模拟器中测试)。天也工作正常。这个方法有任何问题请指导我...

1 个答案:

答案 0 :(得分:0)

document.addEventListener("deviceready",onDeviceReady,false);
                                       function onDeviceReady() {
                                          pictureSource=navigator.camera.PictureSourceType;
                                          destinationType=navigator.camera.DestinationType;
                                          checkConnection();
                                       }
                                       function checkConnection() {
                                          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.CELL]     = 'Cell generic connection';
                                            states[Connection.NONE]     = 'No network connection';

                                        }

现在要检查连接,可以输入以下条件: -

if(networkState == Connection.NONE){
                                                                      navigator.notification.confirm('It looks like your photo could not be shared. Please try again.',onConfirmOne,'Photo Not Shared',['Ok']);
                                         }

还在config.xml中输入以下标记: -

 <feature name="NetworkStatus">
    <param name="ios-package" value="CDVConnection" />
</feature>