How to connect to local network first instead of internet in C# Xamarin Android app?

前端 未结 3 1072
感情败类
感情败类 2020-12-07 05:53

I have a Xamarin Android app. It connects to a “No Internet based Wifi router” for some IOT devices. But it also needs to use mobile’s cellular data for storing some informa

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-07 06:18

    After lot of tries and failures, I was able to implement the approach provided here: Stackoverflow Link

    I changed this code from Java to Xamarin C# and was able to force Cellular or Wifi as the preferred network programmatically.

    My implementation:

    using Android.Net;
    public SomeClass{
        public static Context _context = Android.App.Application.Context;
    
        ....
    
        /// 
        /// Forces the wifi over cellular.
        /// 
        public static void ForceWifiOverCellular()
        {
            ConnectivityManager connection_manager = (ConnectivityManager)_context.GetSystemService(Context.ConnectivityService);
    
            NetworkRequest.Builder request = new NetworkRequest.Builder();
            request.AddTransportType(TransportType.Wifi);
    
            var callback = new ConnectivityManager.NetworkCallback();
            connection_manager.RegisterNetworkCallback(request.Build(), new CustomNetworkAvailableCallBack());
    
        }
    
        /// 
        /// Forces the cellular over wifi.
        /// 
        public static void ForceCellularOverWifi()
        {
            ConnectivityManager connection_manager = (ConnectivityManager)_context.GetSystemService(Context.ConnectivityService);
    
            NetworkRequest.Builder request = new NetworkRequest.Builder();
            request.AddTransportType(TransportType.Cellular);
    
            connection_manager.RegisterNetworkCallback(request.Build(), new CustomNetworkAvailableCallBack());
        }
    }
    
    
    /// 
    /// Custom network available call back.
    /// 
    public class CustomNetworkAvailableCallBack : ConnectivityManager.NetworkCallback
    {
        public static Context _context = Android.App.Application.Context;
    
        ConnectivityManager connection_manager = (ConnectivityManager)_context.GetSystemService(Context.ConnectivityService);
    
        public override void OnAvailable(Network network)
        {
            //ConnectivityManager.SetProcessDefaultNetwork(network);    //deprecated (but works even in Android P)
            connection_manager.BindProcessToNetwork(network);           //this works in Android P
        }
    }
    

    Usage:

    1. Where I need to force Cellular, just call:

    SomeClass.ForceCellularOverWifi();

    1. Where I need to force Wifi, just call:

    SomeClass.ForceWifiOverCellular();

    Hope this helps others.

提交回复
热议问题