Skip to content

Latest commit

 

History

History
122 lines (86 loc) · 3.31 KB

16.cordova-plugin-network-information.md

File metadata and controls

122 lines (86 loc) · 3.31 KB

cordova-plugin-network-information

该插件实现了老版本的Network Information API。他提供了取得移动蜂窝网络和WIFI连接以及是否有可用网络连接信息的功能。

安装

cordova plugin add cordova-plugin-network-information

支持平台

  • Amazon Fire OS
  • Android
  • BlackBerry 10
  • Browser
  • iOS
  • Windows Phone 7 and 8
  • Tizen
  • Windows
  • Firefox OS

Connection

connection可以通过navigator.connection来访问,可以取得设备的网络状态信息。

属性

  • connection.type

Constants

  • Connection.UNKNOWN
  • Connection.ETHERNET
  • Connection.WIFI
  • Connection.CELL_2G
  • Connection.CELL_3G
  • Connection.CELL_4G
  • Connection.CELL
  • Connection.NONE

connection.type

包含设备的网络连接状态和类型。

例子

    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.CELL]     = 'Cell generic connection';
        states[Connection.NONE]     = 'No network connection';

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

    checkConnection();

API 变化

Cordova 2.3.0之前,我们通过navigator.network.connection来拿到Connection对象,但是为了迎合W3C标准,我们将该对象添加到navigator.connectionnavigator.network.connection依然可以使用,但是已经不建议这么使用了。

iOS 提示

  • 小于iOS7的版本是不能识别的网络连接类型的。
    • navigator.connection.type任何情况下都被设置成Connection.CELL

Network-related事件

offline

这个事件是在设备关闭网络连接的时候触发。

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

详细

当设备失去网络连接的时候会触发offline事件,他依赖于Connection API,而且当该事件触发后connection.type会被设置成NONE

你需要使用document.addEventListenerdeviceready后来监听"offline"事件。

例子

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

    function onOffline() {
        // Handle the offline event
    }

iOS 提示

在初始启动的时候,第一个"offline"在至少一秒钟后触发。

online

这个事件是在设备打开网路连接的时候触发。

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

详细

online会在设备从无网络到有可用网络切换的时候触发,他依赖于Connection API,并且触发后connection.type会变成NONE以外的值。

App应该在deviceready之后通过document.addEventListener监听online事件。

例子

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

    function onOnline() {
        // Handle the online event
    }

iOS 提示

在初始启动的时候,online会在至少一秒钟之后被触发,connection.type之前的值是UNKNOWN