首页 > 代码库 > Android 判断网络连接
Android 判断网络连接
1 import android.content.Context; 2 import android.net.ConnectivityManager; 3 import android.net.NetworkInfo; 4 5 /** 6 * 网络工具类 添加网络状态许可:<uses-permission 7 * android:name="android.permission.ACCESS_NETWORK_STATE"/> 8 * 9 * @author benny10 * 11 */12 public class NetworkUtil {13 14 /**15 * 网络连接状态16 * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>17 * @param context18 * 程序上下文19 * @return true:可连接20 */21 public static boolean isNetworkConnected(Context context) {22 if (context != null) {23 ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);24 25 NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();26 if (networkInfo != null) {27 return networkInfo.isAvailable();28 }29 }30 return false;31 }32 33 /**34 * WiFi 网络连接状态35 * <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>36 * @param context37 * 程序上下文38 * @return true:可连接39 */40 public static boolean isWifiConnected(Context context) {41 if (context != null) {42 ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);43 44 NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);45 if (networkInfo != null) {46 return networkInfo.isAvailable();47 }48 }49 return false;50 }51 52 /**53 * Mobile 网络连接状态54 * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>55 * 56 * @param context57 * 程序上下文58 * @return true:可连接59 */60 public static boolean isMobileConnected(Context context) {61 if (context != null) {62 ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);63 64 NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();65 if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {66 return networkInfo.isAvailable();67 }68 }69 return false;70 }71 72 /**73 * 获取网络连接类型74 * @param context 程序上下文75 * @return ConnectivityManager.TYPE_XXXX76 */77 public static int getConnectedType(Context context) {78 if (context != null) {79 ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);80 NetworkInfo mNetworkInfo = connectivityManager.getActiveNetworkInfo();81 if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {82 return mNetworkInfo.getType();83 }84 }85 return -1;86 }87 88 }
Android 判断网络连接
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。