判断当前网络连接类型

作者:追风剑情 发布于:2015-12-24 15:45 分类:Android

         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"/>

 

运行效果

11.png

 

标签: Android

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号