package com.tenlionsoft.baselib.core.receiver;

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

import com.hjq.toast.ToastUtils;
import com.tenlionsoft.baselib.utils.NetworkUtils;

/**
 * 作者: adam
 * 日期: 2022/3/31 - 10:59 上午
 * 邮箱: itgaojian@163.com
 * 描述: 网络状态变化
 */
public class NetworkChangeReceiver extends BroadcastReceiver {
    private static boolean isRegister = false;

    private static class InstanceHolder {
        private static final NetworkChangeReceiver INSTANCE = new NetworkChangeReceiver();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
            NetworkUtils.NetworkType networkType = NetworkUtils.getNetworkType();
            notifyObservers(networkType);
        }
    }


    public static void registerReceiver(Context ctx) {
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        ctx.registerReceiver(InstanceHolder.INSTANCE, filter);
        isRegister = true;
    }

    public static void unRegisterReceiver(Context ctx) {
        if (isRegister) {
            ctx.unregisterReceiver(InstanceHolder.INSTANCE);
        }
    }

    private void notifyObservers(NetworkUtils.NetworkType networkType) {
        if (networkType == NetworkUtils.NetworkType.NETWORK_NO) {
            ToastUtils.show("网络断开,请检查网络");
        }
    }
}
