android

Android判断网络类型和链接状态

位置:首页 > android > 开发技巧,2019-08-27 21:54
Android判断网络package com.hylg.mplibrary; import android.content.Context; import an
Android判断网络
package com.hylg.mplibrary; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; /**
 * 作者:红叶岭谷
 * 时间 2017/8/15.
 * 此类适用于判断网络类型和链接状态的
 */ public class NetworkUtils { /**
     * 判断是否链接()
     * @param context
     * 连接方式详解 https://developer.android.google.cn/reference/android/net/ConnectivityManager.html
     */ public static boolean isNetworkAvailable(Context context){ boolean available = false;
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (manager != null){
            NetworkInfo networkInfo = manager.getActiveNetworkInfo(); if (networkInfo != null){available = networkInfo.isAvailable();}
        } return available;
    } /**
     * 判断当前的网络链接状态
     * @param context
     * @return 返回类型查看网址
     * @return https://developer.android.google.cn/reference/android/net/ConnectivityManager.html
     */ public static int getConnectTypes(Context context){ int connectType = -1;
        ConnectivityManager manager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); if(manager != null){
            NetworkInfo networkInfo = manager.getActiveNetworkInfo(); if(networkInfo != null && networkInfo.isAvailable() && networkInfo.getState() == NetworkInfo.State.CONNECTED){
                connectType = networkInfo.getType();
            }
        } return connectType;
    }
}

TAGS:Android判断网络链接状态

猜你喜欢

NewHot