博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
监听网络状态
阅读量:6610 次
发布时间:2019-06-24

本文共 9549 字,大约阅读时间需要 31 分钟。

网络监听的自己写过一个,刚在github上找到一个,先保存着,以后直接用

原文地址:

使用广播监听网络变化

###需求确认

  • 监听当前网络的状态和类型
  • 类似京东客户端,当网络发生变化时相应更新UI界面

###制作流程

  1. 使用广播监听当前网络的状态。
  2. 配合Application周期注册监听,使得每个界面都继续监听
  3. 抽出BaseActivity类实现回调

#####1.继承BroadcastReceiver实现onReceive方法来判断当前网络是否连接,然后通过更新NetChangeObserver来实现回调。 加入权限

< uses-permission android:name="android.permission.INTERNET" />< uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> < uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />/** * 使用广播去监听网络 * Created by deng on 16/9/13. */public class NetStateReceiver extends BroadcastReceiver {    public final static String CUSTOM_ANDROID_NET_CHANGE_ACTION = "com.zhanyun.api.netstatus.CONNECTIVITY_CHANGE";    private final static String ANDROID_NET_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";    private final static String TAG = NetStateReceiver.class.getSimpleName();    private static boolean isNetAvailable = false;    private static NetUtils.NetType mNetType;    private static ArrayList
mNetChangeObservers = new ArrayList
(); private static BroadcastReceiver mBroadcastReceiver; private static BroadcastReceiver getReceiver() { if (null == mBroadcastReceiver) { synchronized (NetStateReceiver.class) { if (null == mBroadcastReceiver) { mBroadcastReceiver = new NetStateReceiver(); } } } return mBroadcastReceiver; } @Override public void onReceive(Context context, Intent intent) { mBroadcastReceiver = NetStateReceiver.this; if (intent.getAction().equalsIgnoreCase(ANDROID_NET_CHANGE_ACTION) || intent.getAction().equalsIgnoreCase(CUSTOM_ANDROID_NET_CHANGE_ACTION)) { if (!NetUtils.isNetworkAvailable(context)) { LogHelper.e(this.getClass(), "<--- network disconnected --->"); isNetAvailable = false; } else { LogHelper.e(this.getClass(), "<--- network connected --->"); isNetAvailable = true; mNetType = NetUtils.getAPNType(context); } notifyObserver(); } } /** * 注册 * * @param mContext */ public static void registerNetworkStateReceiver(Context mContext) { IntentFilter filter = new IntentFilter(); filter.addAction(CUSTOM_ANDROID_NET_CHANGE_ACTION); filter.addAction(ANDROID_NET_CHANGE_ACTION); mContext.getApplicationContext().registerReceiver(getReceiver(), filter); } /** * 清除 * * @param mContext */ public static void checkNetworkState(Context mContext) { Intent intent = new Intent(); intent.setAction(CUSTOM_ANDROID_NET_CHANGE_ACTION); mContext.sendBroadcast(intent); } /** * 反注册 * * @param mContext */ public static void unRegisterNetworkStateReceiver(Context mContext) { if (mBroadcastReceiver != null) { try { mContext.getApplicationContext().unregisterReceiver(mBroadcastReceiver); } catch (Exception e) { } } } public static boolean isNetworkAvailable() { return isNetAvailable; } public static NetUtils.NetType getAPNType() { return mNetType; } private void notifyObserver() { if (!mNetChangeObservers.isEmpty()) { int size = mNetChangeObservers.size(); for (int i = 0; i < size; i++) { NetChangeObserver observer = mNetChangeObservers.get(i); if (observer != null) { if (isNetworkAvailable()) { observer.onNetConnected(mNetType); } else { observer.onNetDisConnect(); } } } } } /** * 添加网络监听 * * @param observer */ public static void registerObserver(NetChangeObserver observer) { if (mNetChangeObservers == null) { mNetChangeObservers = new ArrayList
(); } mNetChangeObservers.add(observer); } /** * 移除网络监听 * * @param observer */ public static void removeRegisterObserver(NetChangeObserver observer) { if (mNetChangeObservers != null) { if (mNetChangeObservers.contains(observer)) { mNetChangeObservers.remove(observer); } } }}

 

#####2.回调接口

/** * 网络改变观察者,观察网络改变后回调的方法 * Created by deng on 16/9/13. */public interface NetChangeObserver {    /**     * 网络连接回调 type为网络类型     */     void onNetConnected(NetUtils.NetType type);    /**     * 没有网络     */     void onNetDisConnect();}

 

#####3.网络状态工具类

public class NetUtils {    public static enum NetType {        WIFI, CMNET, CMWAP, NONE    }    public static boolean isNetworkAvailable(Context context) {        ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);        NetworkInfo[] info = mgr.getAllNetworkInfo();        if (info != null) {            for (int i = 0; i < info.length; i++) {                if (info[i].getState() == NetworkInfo.State.CONNECTED) {                    return true;                }            }        }        return false;    }    public static boolean isNetworkConnected(Context context) {        if (context != null) {            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();            if (mNetworkInfo != null) {                return mNetworkInfo.isAvailable();            }        }        return false;    }    public static boolean isWifiConnected(Context context) {        if (context != null) {            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);            NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);            if (mWiFiNetworkInfo != null) {                return mWiFiNetworkInfo.isAvailable();            }        }        return false;    }    public static boolean isMobileConnected(Context context) {        if (context != null) {            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);            NetworkInfo mMobileNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);            if (mMobileNetworkInfo != null) {                return mMobileNetworkInfo.isAvailable();            }        }        return false;    }    public static int getConnectedType(Context context) {        if (context != null) {            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();            if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {                return mNetworkInfo.getType();            }        }        return -1;    }    public static NetType getAPNType(Context context) {        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();        if (networkInfo == null) {            return NetType.NONE;        }        int nType = networkInfo.getType();        if (nType == ConnectivityManager.TYPE_MOBILE) {            if (networkInfo.getExtraInfo().toLowerCase(Locale.getDefault()).equals("cmnet")) {                return NetType.CMNET;            } else {                return NetType.CMWAP;            }        } else if (nType == ConnectivityManager.TYPE_WIFI) {            return NetType.WIFI;        }        return NetType.NONE;    }}

 

#####4.在Application中注册

@Override    public void onCreate() {        super.onCreate();        instance = this;        /*开启网络广播监听*/         NetStateReceiver.registerNetworkStateReceiver(instance);    }        @Override    public void onLowMemory() {        if (instance != null) {                    NetStateReceiver.unRegisterNetworkStateReceiver(instance);            android.os.Process.killProcess(android.os.Process.myPid());            exitApp();        }        super.onLowMemory();    }

 

#####5.为了监听每一个Activity就抽取出来一个抽象类

/*** 网络观察者*/protected NetChangeObserver mNetChangeObserver = null;    @Override    protected void onCreate(Bundle savedInstanceState) {// 网络改变的一个回掉类        mNetChangeObserver = new NetChangeObserver() {            @Override            public void onNetConnected(NetUtils.NetType type) {                onNetworkConnected(type);            }            @Override            public void onNetDisConnect() {                onNetworkDisConnected();            }        };        //开启广播去监听 网络 改变事件                NetStateReceiver.registerObserver(mNetChangeObserver);    }    /**     * 网络连接状态     *     * @param type 网络状态     */    protected abstract void onNetworkConnected(NetUtils.NetType type);    /**     * 网络断开的时候调用     */    protected abstract void onNetworkDisConnected();    @Override    protected void onDestroy() {        super.onDestroy();        unbinder.unbind();                     NetStateReceiver.removeRegisterObserver(mNetChangeObserver);    }

 

Use

Maven
com.caption
netmonitorlibrary
1.0.0
pom

 

Gradle
compile 'com.caption:netmonitorlibrary:1.0.0'

 

转载地址:http://rjiso.baihongyu.com/

你可能感兴趣的文章
计算字符串中每种字符出现的次数[Dictionary<char,int>泛型集合用法]
查看>>
UI-text-field
查看>>
在生产环境中安全执行更新删除SQL脚本的技巧
查看>>
ubantu下安装软件
查看>>
PowerDeigner 一个很好的画uml 和建模的软件
查看>>
vs2012创建mvc4项目部署iis所遇到的问题
查看>>
jenkins下载
查看>>
卫语句学习
查看>>
【php】对PHPExcel一些简单的理解
查看>>
文档统一用Word编写之Word写&发送邮件(Office2007)
查看>>
JavaScript的简单继承实现案例
查看>>
第六篇 VIM你值得拥有!
查看>>
项目管理学习笔记之八.课程总结
查看>>
setjmp与longjmp的分析
查看>>
generate ascii table
查看>>
MATLAB绘制3D隐函数曲面的几种方法
查看>>
jquery改变链接移上光标时的颜色实例
查看>>
2013吉林通化邀请赛 1005 GCD and LCM
查看>>
高淇java300集JAVA常用类作业
查看>>
oracle大型数据库系统在AIX/unix上的实战详解 这本书要二版
查看>>