美文网首页Hbuilder+MUI开发5+appHBuilder开发mui 记录
mui中判断网络连接和监听变化的代码段

mui中判断网络连接和监听变化的代码段

作者: 觉子先生 | 来源:发表于2017-02-28 11:31 被阅读1287次
//获取当前设备的网络类型
function plusReady() {
    var types = {};
    types[plus.networkinfo.CONNECTION_UNKNOW] = "Unknown connection";
    types[plus.networkinfo.CONNECTION_NONE] = "None connection";
    types[plus.networkinfo.CONNECTION_ETHERNET] = "Ethernet connection";
    types[plus.networkinfo.CONNECTION_WIFI] = "WiFi connection";
    types[plus.networkinfo.CONNECTION_CELL2G] = "Cellular 2G connection";
    types[plus.networkinfo.CONNECTION_CELL3G] = "Cellular 3G connection";
    types[plus.networkinfo.CONNECTION_CELL4G] = "Cellular 4G connection";
    alert("Network: " + types[plus.networkinfo.getCurrentType()]);
}
if (window.plus) {
    plusReady();
} else {
    document.addEventListener("plusready", plusReady, false);
}
mui.plusReady(function() {
    document.addEventListener("netchange", onNetChange, false);
    //获取当前网络类型
    function onNetChange() {
        var nt = plus.networkinfo.getCurrentType();
        switch (nt) {
            case plus.networkinfo.CONNECTION_ETHERNET:
            case plus.networkinfo.CONNECTION_WIFI:
                mui.toast("当前网络为WiFi");
                break;
            case plus.networkinfo.CONNECTION_CELL2G:
            case plus.networkinfo.CONNECTION_CELL3G:
            case plus.networkinfo.CONNECTION_CELL4G:
                mui.toast("当前网络非WiFi");
                break;
            default:
                mui.toast("当前没有网络");
                break;
        }
    }
});
// 这段代码有疑问,plus.networkinfo.getCurrentType()的值出来是数字吗?且在这放着
document.addEventListener("netchange", function() {
    var network = plus.networkinfo.getCurrentType();
    if(network < 2) {
        if(this.network > 1) {
            plus.nativeUI.toast('您的网络已断开', undefined, '期待乐');
        }
    }
    if(this.network == 3 && network > 3) {
        plus.nativeUI.toast('您网络已从wifi切换到蜂窝网络,浏览会产生流量', undefined, '期待乐', '我知道了');
    }
    this.network=network;
});

相关文章

网友评论

  • 3866b3f2e166:大佬,我想问一下,mui有办法获取手机的ip地址吗,看文档并没有提供相应的api:disappointed_relieved:
    8a792ff5e566:@倾兮意遥 请教大神,页面的ip是个什么东西:clap:
    81fc0fde33aa:@觉子先生 这是获取页面的ip吧。有没有获取手机网络ip的办法
    觉子先生:不是大佬呀:wink: 说下我的做法吧:
    1、新开一个页面,页面上通过js获取ip,页面内容为json格式的字符串,比如:{ip:121.46.1.163}
    2、通过getJSON方法请求上述页面获取ip值:
    $.getJSON( 'http://www.xxx.com/xxx.html', function(data) {
    var ip = data.ip;//获取用户IP
    });

本文标题:mui中判断网络连接和监听变化的代码段

本文链接:https://www.haomeiwen.com/subject/boqxgttx.html