package com.stm.asset.utils;

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

/**
 *
 *类名称:NetworkUtil.java
 *类描述:
 *创建人:张小兵
 *创建时间:2015-1-30 上午11:03:40
 *
 **/
public class NetworkUtil {

	/**
     * 检查当前网络是否可用
     */
    public static boolean isNetworkAvailable(Activity activity) {
        Context context = activity.getApplicationContext();
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null){
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
            if (networkInfo != null && networkInfo.length > 0) {
                for (NetworkInfo item : networkInfo) {
                    if (item.getState() == NetworkInfo.State.CONNECTED){
                        return item.isAvailable();
                    }
                }
            }
        }
        return false;
    }
    
    public static boolean isNetworkAvailable(Context context) {
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null){
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
            if (networkInfo != null && networkInfo.length > 0) {
                for (NetworkInfo item : networkInfo) {
                    if (item.getState() == NetworkInfo.State.CONNECTED){
                        return item.isAvailable();
                    }
                }
            }
        }
        return false;
    }
    
    /**
     * 获取网络类型
     * @return  0 无网络  1wifi 2 手机网络
     */
    public static int getNetworkType(Context context) {
    	final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    	final NetworkInfo info = connectivityManager.getActiveNetworkInfo();  
    	if (info != null) {
    		if (info.getType() == ConnectivityManager.TYPE_WIFI) {
    			return 1;
    		} else {
    			return 2;
    		}
    	} else {
    		return 0;
    	}    	
    }
}
