2

My APP use WifiNetworkSpecifier to connect to a router.

And once connect to the router. APP called

connection_manager.BindProcessToNetwork(network);

After called this function. Even I turn off the WiFi. And turn on the mobile data.

The APP will not able to connect to internet anymore.

If this function is not called. APP will be able to connect to internet through mobile data.

What is the mechanism of BindProcessToNetwork()?

Here is my code. (ref from ref 1 ref 2)

private void RequestNetwork()
{
    var specifier = new WifiNetworkSpecifier.Builder()
        .SetSsid(_ssid.Text)
        .SetWpa2Passphrase(_passphrase.Text)
        .Build();

    var request = new NetworkRequest.Builder()
        .AddTransportType(TransportType.Wifi)
        .RemoveCapability(NetCapability.Internet)
        .SetNetworkSpecifier(specifier)
        .Build();

    var connectivityManager = GetSystemService(ConnectivityService) as ConnectivityManager;

    if (_requested)
    {
        connectivityManager.UnregisterNetworkCallback(_callback);
    }

    connectivityManager.RequestNetwork(request, _callback);


    _requested = true;
}

private class NetworkCallback : ConnectivityManager.NetworkCallback
{
    public Action<Network> NetworkAvailable { get; set; }
    public Action NetworkUnavailable { get; set; }

    public static Context _context = Android.App.Application.Context;

    ConnectivityManager connection_manager = (ConnectivityManager)_context.GetSystemService(Context.ConnectivityService);
    public override void OnAvailable(Network network)
    {
        base.OnAvailable(network);
        NetworkAvailable?.Invoke(network);
        connection_manager.BindProcessToNetwork(network);

    }

    public override void OnUnavailable()
    {
        base.OnUnavailable();
        NetworkUnavailable?.Invoke();
    }
}
CC.Wang
  • 111
  • 1
  • 12

1 Answers1

3

Once BindProcessToNetwork is called, ALL networking sockets are bound to that network for the lifecycle of that app (this is mainly a security feature so packets will not "leak" another network).

You can clear that network binding by calling BindProcessToNetwork again, but passing in null as your network type.

connection_manager.BindProcessToNetwork(null);
SushiHangover
  • 73,120
  • 10
  • 106
  • 165