Android开发之网络状态检测

主要代码:


package com.jun.net.tools;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetTools {
	
	private Context context=null;
	
	
	
	
	public NetTools(Context context) {
		super();
		this.context = context;
	}




	public boolean checkNetState(){
	ConnectivityManager mConnectivityManager = (ConnectivityManager) context
	.getSystemService(Context.CONNECTIVITY_SERVICE);
	NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
	if (mNetworkInfo != null) {
	return mNetworkInfo.isAvailable();
	} 
	return false;
	}
	
public boolean checkWifiState(){
	
	ConnectivityManager mConnectivityManager = (ConnectivityManager) context
	.getSystemService(Context.CONNECTIVITY_SERVICE);
	NetworkInfo mWiFiNetworkInfo = mConnectivityManager
	.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
	if (mWiFiNetworkInfo != null) {
	return mWiFiNetworkInfo.isAvailable();
	} 
	
	
	return false;
}
}

主程序中使用代码:

  btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				NetTools tool=new NetTools(NetActivity.this);
				
				if(tool.checkNetState()||tool.checkWifiState()){
					Toast.makeText(NetActivity.this,"net OK!", Toast.LENGTH_LONG).show();
					
				}else{
					
					Toast.makeText(NetActivity.this,"not!", Toast.LENGTH_LONG).show();
					
				}
				
			}
		});
        
       

如上既可以检测到3G网络或者是Wifi网络

你可能感兴趣的:(Android开发之网络状态检测)