Android中判断网络状态及其种类

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

/** 
 * a tool used for judge the network's status 
 * @author liyangchao 
 * 
 */  
public class NetWorkTools{  
  
    public static booleanisWifi(Context paramContext) {  
  
        return "2".equals(getNetType(paramContext)[0]);  
  
    }  
  
    public static booleanisMobile(Context paramContext) {  
  
        return "1".equals(getNetType(paramContext)[0]);  
  
    }  
  
    public static booleanisNetAvailable(Context paramContext) {  
  
        if ("1".equals(getNetType(paramContext)[0])  
  
        || "2".equals(getNetType(paramContext)[0])) {  
  
            return true;  
  
        }  
  
        return false;  
  
    }  
  
    // public static booleanisNetworkAvailable(Context context) {  
  
    // ConnectivityManager mgr =  
    // (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);  
  
    // NetworkInfo[] info =mgr.getAllNetworkInfo();  
  
    // if (info != null) {  
  
    // for (int i = 0; i < info.length; i++) {  
  
    // if (info[i].getState() ==NetworkInfo.State.CONNECTED) {  
  
    // return true;  
  
    // }  
  
    // }  
  
    // }  
  
     // return false;  
  
    // }  
  
    public static String[] getNetType(Context paramContext) {  
  
        String[] arrayOfString = { "Unknown", "Unknown" };  
  
        PackageManager localPackageManager = paramContext.getPackageManager();  
  
        if (localPackageManager.checkPermission(  
  
        "android.permission.ACCESS_NETWORK_STATE",  
  
        paramContext.getPackageName()) != 0) {  
  
            arrayOfString[0] = "Unknown";  
  
            return arrayOfString;  
  
        }  
  
        ConnectivityManager localConnectivityManager = (ConnectivityManager) paramContext  
  
        .getSystemService("connectivity");  
  
        if (localConnectivityManager == null) {  
  
            arrayOfString[0] = "Unknown";  
  
            return arrayOfString;  
  
        }  
  
        NetworkInfo localNetworkInfo1 = localConnectivityManager  
  
        .getNetworkInfo(1);  
  
        if (localNetworkInfo1 != null  
  
        && localNetworkInfo1.getState() == NetworkInfo.State.CONNECTED) {  
  
            arrayOfString[0] = "2";  
  
            return arrayOfString;  
  
        }  
  
        NetworkInfo localNetworkInfo2 = localConnectivityManager  
  
        .getNetworkInfo(0);  
  
        if (localNetworkInfo2 != null  
  
        && localNetworkInfo2.getState() == NetworkInfo.State.CONNECTED) {  
  
            arrayOfString[0] = "1";  
  
            arrayOfString[1] = localNetworkInfo2.getSubtypeName();  
  
            return arrayOfString;  
  
        }  
  
        return arrayOfString;  
  
    }  
  
}