亲宝软件园·资讯

展开

android网络状态

he先森 人气:0

一、获取当前手机联网方式是WiFi还是手机4G数据

private boolean getNetworkType(){
        ConnectivityManager mConnectivity = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        //检查网络链接
        NetworkInfo info = mConnectivity.getActiveNetworkInfo();
        int netType = mConnectivity.getActiveNetworkInfo().getType();
        if (netType == ConnectivityManager.TYPE_WIFI) {  //WIFI
            ChangYouLog.i(TAG,"当前是WIFI连接 isConnected = "+info.isConnected());
            return info.isConnected();
        } else if (netType == ConnectivityManager.TYPE_MOBILE) {   //MOBILE
            ChangYouLog.i(TAG,"当前是手机网络连接 isConnected = "+info.isConnected());
            return info.isConnected();
        } else {
            ChangYouLog.i(TAG,"当前没有网络连接 isConnected = "+info.isConnected());
            return false;
        }
    }

二、监听手机网络变化

private class MyBroadcastReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {//监听网络连接
                //获取联网状态的NetworkInfo对象
                NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
                if (info != null) {
                    //如果当前的网络连接成功并且网络连接可用
                    if (NetworkInfo.State.CONNECTED == info.getState() && info.isAvailable()) {
                        if (info.getType() == ConnectivityManager.TYPE_WIFI){
                            ChangYouLog.i(TAG,"连接上WiFi");
                        }else if (info.getType() == ConnectivityManager.TYPE_MOBILE){
                            ChangYouLog.i(TAG,"连接上移动网络数据");
                            CYouLbyMicroClient.getInstance().gameEvent("Network_4G_reminder");
                        }
                    } else {
                        ChangYouLog.i(TAG,"网络断开");
                    }
                }
            }
        }
    }

注:需要添加网络状态权限

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

总结

加载全部内容

相关教程
猜你喜欢
用户评论