发表Android8 分钟读完 (大约1184个字) Android BroadCastReceiver 二
01.监听网络状态变化
写一个监听网络状态变化工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| class NetworkUtils {
/** * 标记当前网络状态,分别是:移动数据、Wifi、未连接、网络状态已公布 */ public enum State { MOBILE, WIFI, UN_CONNECTED, PUBLISHED }
/** * 为了避免因多次接收到广播反复提醒的情况而设置的标志位,用于缓存收到新的广播前的网络状态 */ private static State tempState;
/** * 获取当前网络连接状态 * * @param context Context * @return 网络状态 */ public static State getConnectState(Context context) { ConnectivityManager manager = (ConnectivityManager) context. getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = null; if (manager != null) { networkInfo = manager.getActiveNetworkInfo(); } State state = State.UN_CONNECTED; if (networkInfo != null && networkInfo.isAvailable()) { if (isMobileConnected(context)) { state = State.MOBILE; } else if (isWifiConnected(context)) { state = State.WIFI; } } if (state.equals(tempState)) { return State.PUBLISHED; } tempState = state; return state; }
private static boolean isMobileConnected(Context context) { return isConnected(context, ConnectivityManager.TYPE_MOBILE); }
private static boolean isWifiConnected(Context context) { return isConnected(context, ConnectivityManager.TYPE_WIFI); }
private static boolean isConnected(Context context, int type) { //getAllNetworkInfo() 在 API 23 中被弃用 //getAllNetworks() 在 API 21 中才添加 ConnectivityManager manager = (ConnectivityManager) context. getSystemService(Context.CONNECTIVITY_SERVICE); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { NetworkInfo[] allNetworkInfo = new NetworkInfo[0]; if (manager != null) { allNetworkInfo = manager.getAllNetworkInfo(); } for (NetworkInfo info : allNetworkInfo) { if (info.getType() == type) { return info.isAvailable(); } } } else { Network[] networks = new Network[0]; if (manager != null) { networks = manager.getAllNetworks(); } for (Network network : networks) { NetworkInfo networkInfo = manager.getNetworkInfo(network); if (networkInfo.getType() == type) { return networkInfo.isAvailable(); } } } return false; } }
|
阅读更多