监听网络状态

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

原文地址:https://github.com/GHdeng/NetMonitor

使用广播监听网络变化

###需求确认

  • 监听当前网络的状态和类型
  • 类似京东客户端,当网络发生变化时相应更新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<NetChangeObserver> mNetChangeObservers = new ArrayList<NetChangeObserver>();
    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<NetChangeObserver>();
        }
        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
<dependency>
  <groupId>com.caption</groupId>
  <artifactId>netmonitorlibrary</artifactId>
  <version>1.0.0</version>
  <type>pom</type>
</dependency>
Gradle
compile ‘com.caption:netmonitorlibrary:1.0.0‘
时间: 2024-10-11 12:13:20

监听网络状态的相关文章

android 监听网络状态的变化及实战

android 监听网络状态的变化及实际应用 转载请注明博客地址:http://blog.csdn.net/gdutxiaoxu/article/details/53008266 平时我们在请求错误的情况下,通常会进行处理一下,一般来说,主要分为两方面的错误 - 没有网络的错误 - 在有网络的情况下,我们客户端的错误或者服务器端的错误 今天这篇博客主要阐述以下问题 怎样监听网络状态的变化,包括是否打开WiFi,否打开数据网络,当前连接的网络是否可用 网络没有打开情况下的处理,如弹出对话框,跳转到

Android实时监听网络状态

在开发android应用时,涉及到要进行网络访问,时常需要进行网络状态的检查,以提供给用户必要的提醒.一般可以通过ConnectivityManager来完成该工作. ConnectivityManager有四个主要任务: 1.监听手机网络状态(包括GPRS,WIFI, UMTS等) 2.手机状态发生改变时,发送广播 3.当一个网络连接失败时进行故障切换 4.为应用程序提供可以获取可用网络的高精度和粗糙的状态 当我们要在程序中监听网络状态时,只要一下几个步骤即可:  1.处理Recevier接口

Android使用BroadcastReceiver监听网络状态

在开发中,经常会遇到需要判断手机网络状态从而进行各种操作的功能,在这里简单介绍下这种功能的实现. 如题,通过BroadcastReceiver我们能在网络状态改变的时候监听到它. 那么,注册广播的两种方式: 1.静态注册:在AndroidManifest.xml中用标签声明注册,并在标签内用标签设置过滤器. 1 2 3 4 5 6 7 <!--继承BroadcastReceiver,重写onReceiver方法--> <receiver android:name="MyRece

Android监听网络状态

该笔记是用来实时获取网络的状态,有点想QQ的断网提醒,为了以后的工作中用到,就在此处写下关于此判断的代码,下面就是写的一些代码: package com.example.nettest; import receiver.NetReceiver; import android.app.Activity; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.Bun

Android开发之使用广播监听网络状态变化

我们经常需要判断网络状态的变化,如有无网络,所以需要监听网络状态的变化,比如网络断开,网络连接给予友好提示.如何监听网络状态的变化呢,最近工作中需要用到这个,于是就用广播机制来实现了网络状态的监听. 使用广播机制来监听网络状态主要涉及到以下几点: 1.需要自己编写个网络广播接收器,该接收器继承BroadcastReceiver类,用来接收系统发出的广播.比如我自己写了个NetStatusReceiver广播接收器.代码如下: package com.log.system; import andr

android-监听网络状态

1.注册一个广播接收器,监听网络状态private void Start() { IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); filter.addAction(WifiManager.NETWORK_STATE_CHANGED_

动态注册广播,监听网络状态变化,判断网络模式

注册广播监听网络连接和断开状态的变化,判断网络连接模式: private ConnectivityManager mConnectivityManager; private NetworkInfo netInfo; /////////////监听网络状态变化的广播接收器 private BroadcastReceiver myNetReceiver = new BroadcastReceiver() { @Override public void onReceive(Context contex

通过静态广播监听网络变化,在通过回调通知

package com.changim.patient.app.sys.receive; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import com.changim.patient.app.sys.Constants; import com.changim.patient.ap

iOS开发之监听网络连接,改变,断开

做iOS开发时,我们需要监控/监听网络状况,苹果提供了Reachability.h, Reachability.m. 导入Reachability.h 我们可以在 MainViewController的viewDidLoad方法内部写上: [self checkReachability]; 之后,具体方法如下 #pragma mark #pragma mark Reachability Methods #pragma mark - (void)checkReachability { [[NSNo