1

In the Xamarin plugin Connectivity (Xam.Plugin.Connectivity), there is an easy way from the PCL to detect network connectivity changes, like:

CrossConnectivity.Current.ConnectivityChanged += (sender, args) =>
{
    page.DisplayAlert("Connectivity Changed", "IsConnected: " + args.IsConnected.ToString(), "OK");
};

The property IsConnected is read only, so my question is:

Is there a way to manually / programmatically set IsConnected to false or otherwise simulate a lost network connection?

jbyrd
  • 5,287
  • 7
  • 52
  • 86

2 Answers2

0

I don't believe there is a way to programmatically simulate a missing network connection. You can obviously do other things in the simulator and on real devices to achieve what you are looking for. I am not sure what the use case is here, but you could try using something like

CrossConnectivity.Current.IsRemoteReachable("TestHostname", 80, 1000)

rather than relying on the IsConnected property which, as you said is read-only. If you want the user to be "disconnected", hand the method a an invalid hostname, if you want them to be "connected" hand it something valid.

Gunnar
  • 78
  • 1
  • 7
0

Implement a MockConnectivity:

using Plugin.Connectivity.Abstractions;

namespace MyMockConnectivity
{
  public class MockConnectivity : BaseConnectivity
  {
    public void SetIsConnected(bool value)
    {
        OnConnectivityChanged(new ConnectivityChangedEventArgs { IsConnected = value });
    }

    public override bool IsConnected { get; }
...

Use:

using MyMockConnectivity;
using Plugin.Connectivity.Abstractions;
...
MockConnectivity MockConnectivity = new MockConnectivity();
IConnectivity Current = MockConnectivity;

Current.ConnectivityChanged += (sender, args) =>
{
  Debug.WriteLine("IsConnected: " + args.IsConnected);
};

Simulate connectivity changes:

// Simulate network connection
MockConnectivity.SetIsConnected(true);

// Simulate lost network connection
MockConnectivity.SetIsConnected(false);
Benl
  • 2,777
  • 9
  • 13