phonegap3.4 检查网络状态

来源:互联网 发布:自动数字组合软件 编辑:程序博客网 时间:2024/05/17 03:27

参考文档:

https://github.com/apache/cordova-plugin-network-information/blob/master/doc/index.md


1、安装插件

cordova plugin add org.apache.cordova.network-information

2、js脚本

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';    console.log('Connection type: ' + states[networkState]);

3、修改后台java类:NetworkManager

安装好插件后,如果联网状态下,应用运行没有问题,但是在断网状态下,应用无法启动

private JSONObject getConnectionInfo(NetworkInfo info) {        String type = TYPE_NONE;        if (info != null) {            // If we are not connected to any network set type to none            if (!info.isConnected()) {                type = TYPE_NONE;            }            else {                type = getType(info);            }        }        /***********open************/        String extraInfo = null;        if(info != null){        extraInfo = info.getExtraInfo();        }//        String extraInfo = info.getExtraInfo();        /***********************/        Log.d("CordovaNetworkManager", "Connection Type: " + type);        Log.d("CordovaNetworkManager", "Connection Extra Info: " + extraInfo);        JSONObject connectionInfo = new JSONObject();        try {            connectionInfo.put("type", type);            connectionInfo.put("extraInfo", extraInfo);        } catch (JSONException e) { }        return connectionInfo;    }

上面的代码中,info为null,导致应用启动过程中抛出异常,修改了源码


这个异常应该不会是官方的bug,但是在我的应用中会报错,其他的插件用起来都没有问题,唯独这个插件。原因待查明。

0 0