package com.hh.lib_common.connect;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkRequest;

/**
 * Description: $
 *
 * @author xwh
 * time 2024/8/20
 **/
public class NetworkCallbackUtils {

    NetworkCallbackImpl networkCallback;

    public  void registerNetworkCallback(Context context,NetworkCallback callback){
        try {
            networkCallback=new NetworkCallbackImpl(callback);
            NetworkRequest.Builder builder = new NetworkRequest.Builder();
            NetworkRequest request = builder.build();
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            connectivityManager.registerNetworkCallback(request, networkCallback);
        }catch (Exception e){
            if(callback!=null) {
                callback.onAvailable(null);
            }
        }


    }
    public void unregisterNetworkCallback(Context context){
        if(networkCallback!=null){
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            connectivityManager.unregisterNetworkCallback( networkCallback);
        }
    }

}
