当前位置: 代码迷 >> 综合 >> AndroidTools:网络工具-判断网络连接
  详细解决方案

AndroidTools:网络工具-判断网络连接

热度:15   发布时间:2024-01-14 13:25:01.0

AndroidTools Git地址:https://github.com/wisesun7/AndroidTools.git

???? 一般情况下,我们使用ConnectivityManager获取当前网络状态,但该状态只是标明了设备已连接网络,但该网络是否畅通从此处无法得知。此时,我们可以借助ping命令,判断网络是否处于联通状态,然后再执行相应的逻辑。

    public static boolean isNetworkConnected(){
    ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(mContext.CONNECTIVITY_SERVICE);if (null == cm){
    Log.d(TAG,"ConnectivityManager is null!");return false;} else {
    Network[] mNetworkInfo = cm.getAllNetworks();if (null != mNetworkInfo) {
    for (Network network : mNetworkInfo) {
    NetworkInfo networkInfo = cm.getNetworkInfo(network);if (networkInfo != null){
    if (networkInfo.getState() == NetworkInfo.State.CONNECTED){
    return true;}}}}}return false;}public static boolean ping() {
    String result = null;try {
    // ping网址3次Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 www.baidu.com" );// ping的状态int status = p.waitFor();if (status == 0) {
    result = "success";return true;} else {
    result = "failed";}} catch (IOException e) {
    result = "IOException";} catch (InterruptedException e) {
    result = "InterruptedException";} finally {
    Log.d(TAG, "ping result = " + result);}return false;}