1

I need to make a simple callback in Xamarin, to check if the network status is connected or disconnected.

I have so far been doing it with this code:

class NetworkControl : INetworkControl
{
    private readonly INetworkControl.ICallback _callback;
    private readonly Context _context;
    private readonly NetworkBroadcastReceiver _receiver = new NetworkBroadcastReceiver();

    public NetworkControl(INetworkControl.ICallback callback, Context context)
    {
        _callback = callback;
        _context = context;
        IntentFilter filter = new IntentFilter(ConnectivityManager.ConnectivityAction);
        context.RegisterReceiver(_receiver, filter);
    }

    public INetworkControl.ICallback Callback => _callback;

    public INetworkControl.NetworkStatus Status
    {
        get
        {
            var current = Connectivity.NetworkAccess;
            if (current == NetworkAccess.Internet)
            {
                return INetworkControl.NetworkStatus.Connected;
            }
            return INetworkControl.NetworkStatus.Disconnected;
        }
    }
}


class NetworkBroadcastReceiver : BroadcastReceiver
{

    private static String TAG = "NetworkBroadcastReceiver";

    public override void OnReceive(Context context, Intent intent)
    {


       if (ShellBridge.Instance != null)
       {
           if (intent.Action.Equals(ConnectivityManager.ConnectivityAction))
           {
               NetworkInfo ni = (NetworkInfo)intent.Extras.Get(ConnectivityManager.ExtraNetworkInfo);
               if (ni.isConnected) 
               {
                   // do something if connected
                   ShellBridge.Instance.NetworkBridge.Callback.NetworkStatusChanged(INetworkControl.NetworkStatus.Connected);
               } else 
               {
                   ShellBridge.Instance.NetworkBridge.Callback.NetworkStatusChanged(INetworkControl.NetworkStatus.Connected);
               }

           }

       }

    }

The problem is, the function ConnectivityManager.ConnectivityAction in the Intent creating is depricated, and will soon be obsolete. After searching, I found that the pendingIntent should be used for that, but I could not find any valid example of how to use it.

The closest to what I need is this:

https://stackoverflow.com/questions/58588132/how-to-use-registernetworkcallback-with-pendingintent

But, it has not all the information I need. I need it to be all programmatically, without changing the manifest, for, my app should be a fore- and background app.

Please help, and thank you for your time.

Elydasian
  • 2,016
  • 5
  • 23
  • 41

2 Answers2

1

You don't need to reinvent the wheel. You can achieve all that with Xamarin Essentials' Connectivity.

Besides checking if there is a connectivity like this:

var current = Connectivity.NetworkAccess;
if (current == NetworkAccess.Internet)
{
    // Connection to internet is available
}

you can also track when the connectivity type changes:

public class ConnectivityTest
{
    public ConnectivityTest()
    {
        // Register for connectivity changes, be sure to unsubscribe when finished
        Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
    }

    void Connectivity_ConnectivityChanged(object sender, ConnectivityChangedEventArgs e)
    {
        var access = e.NetworkAccess;
        var profiles = e.ConnectionProfiles;
    }
}
Mihail Duchev
  • 4,691
  • 10
  • 25
  • 32
  • 1
    thx, I also found this solution, but I need it to be using the callback, bc it is one of many things the callback is monitoring in different times, I need this to work with the pendinfIntent (for me also, I want to learn it that way too :)), have an upvote anyway – Elydasian Jun 02 '20 at 07:57
1

You can take a look at NetworkCallback .

public class ConnectionStateMonitor : NetworkCallback  
    {
        NetworkRequest networkRequest;

        public ConnectionStateMonitor()
        {
            networkRequest = new NetworkRequest.Builder().
                AddTransportType(TransportType.Cellular).
                AddTransportType(TransportType.Wifi).Build();
        }

        public void enable(Context context) {
            ConnectivityManager connectivityManager = context.GetSystemService(Context.ConnectivityService) as ConnectivityManager;
            connectivityManager.RegisterNetworkCallback(networkRequest, this);
        }

        public override void OnAvailable(Network network)
        {
            //network available
        }

        public override void OnLost(Network network)
        {
            //network lost
        }
    }

Usage

You just need to instantiate the class ConnectionStateMonitor and enable it , you could detect the network status with the method OnAvailable and OnLost .

ConnectionStateMonitor m = new ConnectionStateMonitor ();
m.enable(context);

Refer

https://github.com/xamarin/Essentials/issues/512

ConnectivityManager.CONNECTIVITY_ACTION deprecated

ColeX
  • 14,062
  • 5
  • 43
  • 240
  • Thank you for your time, I also found this one too, but as I said Mihail, I want to know a way to use the paddingIntent, – Elydasian Jun 04 '20 at 08:29
  • After a lot of searching, I didn't found any example on how to use the paddingIntent, and have decided to use this solution, but can u help me a bit, I do not understand how should I change my code, in order to implement yours? – Elydasian Jun 04 '20 at 12:40
  • So, I should instantiate the class within the NetworkControl constructor (where i registered the receiver (adn get rid of the reciever ofc)) – Elydasian Jun 04 '20 at 12:50
  • yes ,onAvailable() gets called when Wi-Fi connects to a network and onLost() gets called when Wi-Fi disconnects from a network. – ColeX Jun 04 '20 at 12:55
  • ok, thank you very much for your time, I'll accept the answer, and IF by any chance, you come up/across with the answer that includes peddingIntent, please tag me :) – Elydasian Jun 04 '20 at 12:57