使用 cordova-plugin-network-information 插件

检测网络连接的当前状态并响应可能发生的任何更改,可以使用多个插件之一来完成。这个例子是关于 cordova-plugin-network-information 插件的。

将插件添加到项目中:

cordova plugin add cordova-plugin-network-information

在 Cordova deviceready 事件之后,通过 navigator.connection 可以获得连接对象。type 属性包含当前网络状态:

document.addEventListener("deviceready", function() {
    var networkState = navigator.connection.type;
}, false);

networkState 现在包含以下常量之一:

Connection.UNKNOWN  //  Unknown connection
Connection.ETHERNET //  Ethernet connection
Connection.WIFI     //  WiFi connection
Connection.CELL_2G  //  Cell 2G connection
Connection.CELL_3G  //  Cell 3G connection
Connection.CELL_4G  //  Cell 4G connection
Connection.CELL     //  Cell generic connection
Connection.NONE     //  No network connection

检测网络连接的变化可以通过将函数挂钩到 onlineoffline 事件来完成:

document.addEventListener("online", function() {
    // device went online
    var networkState = navigator.connection.type; // Get new network state
    ...
}, false);

document.addEventListener("offline", function() {
    // device went offline
    var networkState = navigator.connection.type; // Get new network state
    ...
}, false);