前言:
通过广播接收器实现.
1.自定义一个广播接收器 继承自:BroadcastReceiver
2.代码(重写onReceiver方法):
@Override public void onReceive(Context context, Intent intent) { //API小于23 if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) { ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE); NetworkInfo wifiNetworkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo dataNetworkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (wifiNetworkInfo.isConnected() || dataNetworkInfo.isConnected()) { evevt.onNetChange(1); } else { evevt.onNetChange(0); } } else {//API大于23时 System.out.println("API level 大于23"); //获得ConnectivityManager对象 ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE); Network[] networks = connMgr.getAllNetworks(); StringBuilder sb = new StringBuilder(); //通过循环将网络信息逐个取出来 for (int i = 0; i < networks.length; i++) { //获取ConnectivityManager对象对应的NetworkInfo对象 NetworkInfo networkInfo = connMgr.getNetworkInfo(networks[i]); if (networkInfo.isConnected()){ evevt.onNetChange(1); }else { evevt.onNetChange(0); } } }3.添加权限 与 动态注册.
4.通过接口回调将状态值返回去,执行相应逻辑处理.