Forum Xamarin.Android

Using Network Access and ConnectivityManager, help needed

axaaxa Member ✭✭✭
edited March 2019 in Xamarin.Android

Might anyone be able to show me if there are xamarin/c# examples of using Network Access and the ConnectivityManager as in these examples:

https://developer.android.com/training/wearables/data-layer/network-access.html

https://github.com/googlesamples/android-WearHighBandwidthNetworking/blob/master/Wearable/src/main/java/com/example/android/wearable/wear/wearhighbandwidthnetworking/MainActivity.java

Im trying to figure out how to gain access to the internet resource when a WearOS device has Bluetooth on and active, and thus setting the wifi connection disconnected/off

networkCallback = object : ConnectivityManager.NetworkCallback() {
    override fun onAvailable(network: Network) {
        if (bindProcessToNetwork(network)) {
            // socket connections will now use this network
        } else {
            // app doesn't have android.permission.INTERNET permission
        }
    }
}

In particular I do not understand how ConnectivityManager.NetworkCallback() could be assigned.
In Xamarin ConnectivityManager.NetworkCallback() is a class.
In Xamarin onAvailable is a method that takes a parameter, i would expect one or both of these to be events or at least some type of delegate.

Help here would be MASSIVELY appreciated.

Answers

  • timbyte5timbyte5 Member

    Hey there, I'm aware that your post is quite old but I have found out how to use NetworkCallback in Xamarin.Android and it may help you or some people who have the same question!

    What you'll want to do is to create a new class, deriving from ConnectivityManager.NetworkCallback:

    class AppNetworkCallback : ConnectivityManager.NetworkCallback
    {
        public override void OnAvailable(Network network)
        {
            base.OnAvailable(network);
            Console.WriteLine("******  network available ******");
        }
    }
    

    This class can then be used as the callback:

    ConnectivityManager conn = (ConnectivityManager)ApplicationContext.GetSystemService(Context.ConnectivityService);
    NetworkRequest.Builder builder = new NetworkRequest.Builder();
    
    conn.RegisterNetworkCallback(builder.Build(), new AppNetworkCallback());
    
Sign In or Register to comment.