[小代码]ConnectivityReceiver网络监听类


下面代码,监听网络状态变化,当网络连接开启或关闭时将调用回调函数。

使用方法,你需创建一个 实例,同时在你的onCreate()和onResume方法中调用 bind(this)
在onPause方法调用unbind()

然后你可以做两件事:
1.在任何时刻调用hasConnection()检查网络状态。
2.实现OnNetworkAvailableListener接口,网络状态变化时会得到通知。

你需要以下权限:

android.permission.INTERNET
android.permission.ACCESS_NETWORK_STATE

public class ConnectivityReceiver extends BroadcastReceiver {
    
    public static interface OnNetworkAvailableListener {
        public void onNetworkAvailable();
        public void onNetworkUnavailable();
    }
    
    private final ConnectivityManager connectivityManager;
    private OnNetworkAvailableListener onNetworkAvailableListener;
    private boolean connection = false;
    
    public ConnectivityReceiver(Context context) {
        connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        checkConnectionOnDemand();
    }
    
    public void bind(Context context) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        context.registerReceiver(this, filter);
        checkConnectionOnDemand();
    }
    
    public void unbind(Context context) {
        context.unregisterReceiver(this);
    }

    private void checkConnectionOnDemand() {
        final NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info == null || info.getState() != State.CONNECTED) {
            if (connection == true) {
                connection = false;
                if (onNetworkAvailableListener != null) onNetworkAvailableListener.onNetworkUnavailable();
            }
        }
        else {
            if (connection == false) {
                connection = true;
                if (onNetworkAvailableListener != null) onNetworkAvailableListener.onNetworkAvailable();
            }
        }
    }
    
    @Override
    public void onReceive(Context context, Intent intent) {
        if (connection == true && intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {
            connection = false;
            if (onNetworkAvailableListener != null) {
                onNetworkAvailableListener.onNetworkUnavailable();
            }
        }
        else if (connection == false && !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {
            connection = true;
            if (onNetworkAvailableListener != null) {
                onNetworkAvailableListener.onNetworkAvailable();
            }
        }
    }
    
    public boolean hasConnection() {
        return connection;
    }
    
    public void setOnNetworkAvailableListener(OnNetworkAvailableListener listener) {
        this.onNetworkAvailableListener = listener;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值