网络管理类

网络管理类

package com.example.framework.manager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.util.LinkedList;
import java.util.List;

public class ShopManager {

    private Context context;
    private boolean isConnected;
    private List<IConnectListener> connectListeners = new LinkedList<>();

    public void init(Context context) {
        this.context = context;

        getCurrentConnectStatus();
        initReceiver();
    }

    private void getCurrentConnectStatus() {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            isConnected = true;
        } else {
            isConnected = false;
        }

    }


    private void initReceiver() {
        IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        context.registerReceiver(broadcastReceiver, intentFilter);

    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                getCurrentConnectStatus();
                notifyConnectChanged();
            }
        }
    };

    private void notifyConnectChanged() {
        for (IConnectListener connectListener : connectListeners) {
            if (isConnected) {
                connectListener.onConnected();
            } else {
                connectListener.onDisconnected();
            }
        }
    }

    public interface IConnectListener {
        void onConnected();
        void onDisconnected();
    }


    public synchronized void registerConnectListener(IConnectListener iConnectListener) {
        if (!connectListeners.contains(iConnectListener)) {
            connectListeners.add(iConnectListener);
        }
    }


    public synchronized void unregisterConnectListener(IConnectListener iConnectListener) {
        if (connectListeners.contains(iConnectListener)) {
            connectListeners.remove(iConnectListener);
        }
    }

    private static ShopManager shopManager;

    public static synchronized ShopManager getInstance() {
        if (shopManager == null) {
            shopManager = new ShopManager();
        }
        return shopManager;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值