如何在C#Xamarin Android应用程序中首先连接到本地网络而不是互联网?
我有一个Xamarin Android应用程序.它连接到某些物联网设备的不基于Internet的Wifi路由器".但是它还需要使用移动电话的蜂窝数据在Dropbox上存储一些信息.
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 information on Dropbox.
现在,它的工作方式如下:
Now this is working as follows:
- 我可以通过编程方式打开/关闭Wifi连接.
- 我无法打开/关闭移动数据(自Android L起).禁止在非root用户的设备上使用.
- 当我的手机连接到此本地Wifi路由器并且蜂窝数据"也处于打开状态时,Android的默认工作方式是,它使用来自蜂窝网络的Internet连接,并且我对Dropbox的所有呼叫均正常进行.
- 但是,当本地Wifi没有互联网"时,这种对Cellular的偏爱导致我的应用无法连接到本地设备.假设我的设备之一正在端口9000上的IP 192.168.2.3上侦听,当我尝试连接到它时,我的代码通过蜂窝数据搜索它并返回未找到的主机.
- 在这种情况下,有没有办法连接到本地设备?
- 作为一种解决方法,我手动提供了模式弹出窗口,以指示用户在需要非" Dropbox调用(例如,连接到IOT设备)时禁用Cellular.但是,由于用户必须继续手动更改网络,因此这不是良好的用户体验.我希望代码以更透明的方式处理此问题.
请告知.
经过多次尝试和失败,我能够实现此处提供的方法: Stackoverflow链接
After lot of tries and failures, I was able to implement the approach provided here: Stackoverflow 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
}
}
用法:
- 我需要强制Cellular的地方,只需致电:
SomeClass.ForceCellularOverWifi();
SomeClass.ForceCellularOverWifi();
- 需要强制Wifi的地方,只需致电:
SomeClass.ForceWifiOverCellular();
SomeClass.ForceWifiOverCellular();
希望这对其他人有帮助.
Hope this helps others.