前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android封装网络检测的相关类

Android封装网络检测的相关类

作者头像
Vaccae
发布2019-07-24 11:21:52
6810
发布2019-07-24 11:21:52
举报
文章被收录于专栏:微卡智享微卡智享

当我们手机的APP在用到网络时一般会先检测手机是不是能上网,或是上网是用的wifi还是手机流量,于是就把相关的网络检测信息封装到一个类里,直接调用方法即可实现了.

我们新建一个networkUtils的类

网络是否可用

public static boolean isNetworkAvailable(Context context) { ConnectivityManager connectivity = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity == null) { } else { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; }

Gps是否打开

public static boolean isGpsEnabled(Context context) { LocationManager locationManager = ((LocationManager) context .getSystemService(Context.LOCATION_SERVICE)); List<String> accessibleProviders = locationManager.getProviders(true); return accessibleProviders != null && accessibleProviders.size() > 0; }

wifi是否打开

public static boolean isWifiEnabled(Context context) { ConnectivityManager mgrConn = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); TelephonyManager mgrTel = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); return ((mgrConn.getActiveNetworkInfo() != null && mgrConn .getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED) || mgrTel .getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS); }

判断当前网络是否是wifi网络

public static boolean isWifi(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) { return true; } return false; }

判断当前网络是否是3G网络

public static boolean isMonet(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) { return true; } return false; }

检测网络

public static boolean checkNet(Context context) { try { ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo info = connectivity.getActiveNetworkInfo(); if (info != null && info.isConnected()) { if (info.getState() == NetworkInfo.State.CONNECTED) { return true; } } } } catch (Exception e) { return false; } return false; }

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-03-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 微卡智享 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档