public void onClick(View view) { TextView textView = (TextView) findViewById(R.id.infoText); ConnectivityManager con=(ConnectivityManager)getSystemService(Activity.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = con.getActiveNetworkInfo();//获取网络的连接情况 if(null == activeNetInfo) { textView.setText("NetworkInfo: NULL, 无网络连接"); return; } if(!activeNetInfo.isAvailable()){ textView.setText("网络无效"); return; } State state = activeNetInfo.getState(); if(state.equals(State.DISCONNECTED)){ textView.setText("网络已断开"); return; } if(state.equals(State.DISCONNECTED)){ textView.setText("网络正在断开..."); return; } if(state.equals(State.CONNECTING)){ textView.setText("网络连接中..."); return; } String info = ""; if(state.equals(State.CONNECTED)){ info += "网络已连接上\n"; } int netType = activeNetInfo.getType(); info += "网络类型: "+netType+", "+activeNetInfo.getTypeName() + "\n"; info += "详细信息:\n" + activeNetInfo.toString(); textView.setText(info); }
需要添加以下权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
运行效果