android 中怎么判断网络连接,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
//判断是否为wifi连接 public boolean isWifiConnected(Context context) { if (context != null) { ConnectivityManager mConnectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mWiFiNetworkInfo = mConnectivityManager .getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (mWiFiNetworkInfo != null) { return mWiFiNetworkInfo.isAvailable(); } } return false; } //判断是否为网络连接是否正常 public boolean isNetworkConnected(Context context) { if (context != null) { ConnectivityManager mConnectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mNetworkInfo = mConnectivityManager .getActiveNetworkInfo(); if (mNetworkInfo != null) { return mNetworkInfo.isAvailable(); } } return false; } //判断网络连接类型 public static int getConnectedType(Context context) { if (context != null) { ConnectivityManager mConnectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mNetworkInfo = mConnectivityManager .getActiveNetworkInfo(); if (mNetworkInfo != null && mNetworkInfo.isAvailable()) { return mNetworkInfo.getType(); } } return -1; } //判断手机sim卡类型 public static String get(Context context) { TelephonyManager telManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); String operator = telManager.getSimOperator(); if (operator != null) { if (operator.equals("46000") || operator.equals("46002")) { // 中国移动 return "移动"; } else if (operator.equals("46001")) { return "联通"; // 中国联通 } else if (operator.equals("46003")) { return "电信"; // 中国电信 } } return ""; } //判断手机是否能正常上网 进行ping操作, 即使判断手机连接了wifi了(热点没有上网),手机还是不能上网 private static final boolean ping() { String result = null; try { String ip = "www.baidu.com";// 除非百度挂了,否则用这个应该没问题~ Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);//ping3次 // 读取ping的内容,可不加。 InputStream input = p.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(input)); StringBuffer stringBuffer = new StringBuffer(); String content = ""; while ((content = in.readLine()) != null) { stringBuffer.append(content); } Log.i("TTT", "result content : " + stringBuffer.toString()); // PING的状态 int status = p.waitFor(); if (status == 0) { result = "successful~"; return true; } else { result = "failed~ cannot reach the IP address"; } } catch (IOException e) { result = "failed~ IOException"; } catch (InterruptedException e) { result = "failed~ InterruptedException"; } finally { Log.i("TTT", "result = " + result); } return false; }
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。