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

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用
/** 
 * 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;  
  
    }  
  
}

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:纯java实现读写windows注册表代码

下一篇:Java全角字符串转换为半角字符串