package util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
public class NetUtil {
public static final int NETWORN_NONE=0;
public static final int NETWORN_WIFI=1;
public static final int NETWORN_MOBLE=2;
public static int getNetworkState(Context context){
//获得ConnectivityManager对象
ConnectivityManager connManager=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
//wifi状态的获取与判断---------------
State state=connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
if(state==State.CONNECTED||state==State.CONNECTING){//连接状态和正在连接状态
return NETWORN_WIFI;//返回1
}
//------------------------
//手机移动网络状态的获取----------------------
state=connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
if(state==State.CONNECTED||state==State.CONNECTING){
return NETWORN_MOBLE;//2
}
//-------------------------
return NETWORN_NONE;//如果没有移动网络和手机网络则返回0代表无网络
}
}
//这里主要涉及到两个类一个是ConnectivityManager类和State类
ConnectivityManager类通过context.getSystem(Context.CONNECTIVITY_SERVICE)获得
ConnectivityManager对象.getNetworkInfo(ConnectivityManager.TYPE_WIFI)返回NetworkInfo类直接.getState()可以获得网络状态类然后判断state等于State.CONNECTED或者是State.CONNECTING连接上了还是正在连接