本文主要是介绍BroadcastReceiver获取手机网络状态,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
public class NetReceiver extends BroadcastReceiver {/*** 枚举网络状态 NET_NO:没有网络 NET_2G:2g网络 NET_3G:3g网络 NET_4G:4g网络 NET_WIFI:wifi* NET_UNKNOWN:未知网络*/public static enum NetState {NET_NO, NET_2G, NET_3G, NET_4G,NET_WIFI, NET_MOBILE, NET_UNKNOWN};public static List<NetEventHandle> ehList = new ArrayList<NetEventHandle>();public static interface NetEventHandle {/*** 网络状态码* * @param netCode*/void netState(NetState netCode);}@Overridepublic void onReceive(Context context, Intent intent) {// 向所有实现接口的activity传递消息for (NetEventHandle e : ehList) {e.netState(isConnected(context));}}/*** 判断当前是否网络连接* * @param context* @return 状态码*/public NetState isConnected(Context context) {NetState stateCode = NetState.NET_NO;ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo ni = cm.getActiveNetworkInfo();if (ni != null && ni.isConnectedOrConnecting()) {switch (ni.getType()) {case ConnectivityManager.TYPE_WIFI:stateCode = NetState.NET_WIFI;break;case ConnectivityManager.TYPE_MOBILE:switch (ni.getSubtype()) {case TelephonyManager.NETWORK_TYPE_GPRS: // 联通2gcase TelephonyManager.NETWORK_TYPE_CDMA: // 电信2gcase TelephonyManager.NETWORK_TYPE_EDGE: // 移动2gcase TelephonyManager.NETWORK_TYPE_1xRTT:case TelephonyManager.NETWORK_TYPE_IDEN:stateCode = NetState.NET_2G;break;case TelephonyManager.NETWORK_TYPE_EVDO_A: // 电信3gcase TelephonyManager.NETWORK_TYPE_UMTS:case TelephonyManager.NETWORK_TYPE_EVDO_0:case TelephonyManager.NETWORK_TYPE_HSDPA:case TelephonyManager.NETWORK_TYPE_HSUPA:case TelephonyManager.NETWORK_TYPE_HSPA:case TelephonyManager.NETWORK_TYPE_EVDO_B:// case TelephonyManager.NETWORK_TYPE_EHRPD:// case TelephonyManager.NETWORK_TYPE_HSPAP:stateCode = NetState.NET_3G;break;// case TelephonyManager.NETWORK_TYPE_LTE:// stateCode = NetState.NET_4G;// break;default:stateCode = NetState.NET_MOBILE;}break;default:stateCode = NetState.NET_UNKNOWN;}}return stateCode;}}
别忘了在AndroidMinestfest.xml中静态注册:
<receiver android:name=".NetReceiver" ><intent-filter><action android:name="android.net.conn.CONNECTIVITY_CHANGE" /></intent-filter></receiver>
这篇关于BroadcastReceiver获取手机网络状态的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!