上期不是介绍了一下怎么使用.NET MAUI来进行自己手机的Android代码调试嘛。
本期介绍如何在Android平台上来实现Wifi IP地址的获取。 首先打开我们的项目,在MainPage.xaml中加入我们的页面布局
<?xml version="1.0" encoding="utf-8" ?><ContentPage xmlns="https://pic.qr2c.cn/dotnet/2021/maui" xmlns:x="https://pic.qr2c.cn/winfx/2009/xaml" x:Class="MAUIapp.MainPage"> <StackLayout Orientation="Vertical" Spacing="10"> <Button x:Name="Button" Text="Click Me" Clicked="OnButtonClick"/> <Label x:Name="Label" Text="0" />
<Image x:Name="PictureBox" Source="dotnet_bot.png" WidthRequest="100" HeightRequest="100" Aspect="AspectFit" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" />
</StackLayout>
</ContentPage>
我们放置一个容器StackLayout,他的Orientation属性设置为Vertical,代表这个容器的内容是垂直分布,控件间距为10
分别添加按钮,标签,图片。按钮设置回调函数OnButtonClick
private void OnButtonClick(object sender, EventArgs e){ }
接着就可以在 MainPage.xaml.cs中添加我们的回调函数。 ** Wifi地址获取实现 **
之后我们需要实现Android设备获取IP地址的函数。
namespace MAUIapp{ public partial class App : Application { public App() { InitializeComponent();
MainPage = new AppShell(); } }
public interface IWifiService { string GetIpAddress(); }
}
首先在App.cs中添加一个Wifi的类(名字随意),注意和上面的App的类分开,这个类我们先添加一个内容,获取IP地址的函数。
接着在Playforms分平台中,添加文件夹分类我们的文件,添加Wifi的类,我们在其中实现我们的代码。
namespace MAUIapp.Platforms.Android.Servers{ public class AndroidWifiService : IWifiService { public string GetIpAddress() { // 获取当前应用程序的上下文 Context context = MauiApplication.Current.ApplicationContext;
// 使用上下文获取 WifiManager WifiManager wifiManager = (WifiManager)context.GetSystemService(Context.WifiService);
// 检查 WiFi 是否启用 if (wifiManager != null && wifiManager.IsWifiEnabled) { // 获取连接的 WiFi 信息 WifiInfo wifiInfo = wifiManager.ConnectionInfo;
// 获取 IP 地址 int ipAddress = wifiInfo.IpAddress; string ipAddressString = FormatIpAddress(ipAddress);
return ipAddressString; }
// 如果 WiFi 未启用或未连接,则返回 "No IpAddress" return "No IpAddress"; }
private string FormatIpAddress(int ipAddress) { byte[] byteAddress = BitConverter.GetBytes(ipAddress); IPAddress ip = new IPAddress(byteAddress); return ip.ToString(); }
} }
这里我们重新创建了一个类,用来继承父类,为Android提供特定接口。 我们使用Context类来获取Wifi的信息, 在 Android
开发中,Context 是一个关键类,它是一个抽象类,继承自 Object 类。Context 类提供了应用程序的全局信息和访问应用程序资源的方法。它是
Android 应用程序中的关键组件,几乎在每个 Android 应用程序中都会用到。 利用WifiManage来获取Wifi设备信息。
之后写一个重新写一个函数FormatIpAddress来获取IP地址。
在 MainPage.xaml.cs中调用我们的函数。
private void OnButtonClick(object sender, EventArgs e) {#if __ANDROID__ try { AndroidWifiService wifiService = new AndroidWifiService(); string ipAddress = wifiService.GetIpAddress(); Label.Text = ipAddress; } catch (Exception ex) { // 捕捉异常并在调试器中查看 Label.Text = ($"Exception: {ex.Message}"); }#endif#if WINDOWS10_0_17763_0_OR_GREATER Label.Text = "这里是Windows专属";
#endif
}
public interface IWifiService { string GetIpAddress(); }
记得加上#if __ANDROID__来区分不同的设备,以及这里重新声明一下IWifiServerce。
运行我们的代码。
点击按钮之后,即可显示IP地址。