安卓网络监听

1.判断当前网络类型:
是否是无线连接状态:

public boolean isWifiConnected(Context context) {
 ConnectivityManager connMgr
                = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return wifiNetInfo != null && wifiNetInfo.isConnected();
        }
判断移动网络是否连接(在WiFi开启状态下也能检测)
public boolean isMobileConnect(Context context){
        ConnectivityManager connManager
                = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        Class cmClass         = connManager.getClass();
        Class[] argClasses     = null;
        Object[] argObject     = null;
        Boolean isOpen = false;
        try
        {
            Method method = cmClass.getMethod("getMobileDataEnabled", argClasses);

            isOpen = (Boolean) method.invoke(connManager, argObject);
            if(isOpen==true){
                return true;
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return false;
    }

另外一种判断当前是否是移动网络类型的方法(此方法在WiFi已连接状态下无效)


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return Settings.Global.getInt(context.getContentResolver(), "mobile_data", 0) == 1;
        }

        ConnectivityManager connMgr
                = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo.State mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
        return mobile != null && mobile.isConnected;
    }

下面介绍网络连接的开关:
首先看一下移动网络的开关:

// 打开或关闭移动网络连接
    public void toggleMobileConnect(boolean enableMobile) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // todo
//            toggleMobileConnectForLollipop(enableMobile);
            return ;
        }

        ConnectivityManager connMgr
                = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        Class<?> cmClass = connMgr.getClass();
        Class<?>[] argClasses = new Class[1];
        argClasses[0] = boolean.class;

        Method method;
        try {
            method = cmClass.getMethod("setMobileDataEnabled", argClasses);
            method.invoke(connMgr, enableMobile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

此方法在安卓5.0之前的版本是可以用的,我用的魅族5.1系统亲测无效。
无线网的开关相对来说比较简单,主要用到WifiManager,方法如下:

public void openWifi() {
    WifiManager wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
     wifiManager.setWifiEnabled(true);
}

关闭只需设为false即可。
我的第一篇博客就介绍到这里了,下次有值得分享的代码再跟大家分享。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值