更新时间:2022-06-22 22:46:45
经过多次尝试和失败,我能够实现此处提供的方法: ***链接
After lot of tries and failures, I was able to implement the approach provided here: *** Link
我将此代码从Java更改为Xamarin C#,并能够以编程方式强制Cellular或Wifi作为首选网络.
I changed this code from Java to Xamarin C# and was able to force Cellular or Wifi as the preferred network programmatically.
我的实现:
using Android.Net;
public SomeClass{
public static Context _context = Android.App.Application.Context;
....
/// <summary>
/// Forces the wifi over cellular.
/// </summary>
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());
}
/// <summary>
/// Forces the cellular over wifi.
/// </summary>
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());
}
}
/// <summary>
/// Custom network available call back.
/// </summary>
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
}
}
用法:
SomeClass.ForceCellularOverWifi();
SomeClass.ForceCellularOverWifi();
SomeClass.ForceWifiOverCellular();
SomeClass.ForceWifiOverCellular();
希望这对其他人有帮助.
Hope this helps others.