If you are writing an Android app, why use Maui? Why not just make it an Android-only app using either <TargetFramework>net9.0-android35</TargetFramework>
or <TargetFramework>net8-android</TargetFramework>
? That way, you only need to follow Android's documentation. What sort of device are you trying to connect to?
How to read data from Serial Ports on Android using MAUI
Hi everyone,
I'm working on a .NET MAUI app for Android and I’m having some trouble. Right now, my code just displays the connected USB devices info, but I actually need to read data from serial ports instead.
Here's the code I have so far:
#if ANDROID
using Android.Content;
using Android.Hardware.Usb;
#endif
namespace MauiApp2
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void OnCounterClicked(object sender, EventArgs e)
{
#if ANDROID
var act = Platform.CurrentActivity;
UsbManager manager = (UsbManager)act.GetSystemService(Context.UsbService);
IDictionary<string, UsbDevice> devicesDictionary = manager.DeviceList;
if (devicesDictionary != null && devicesDictionary.Count > 0)
{
string devicesInfo = "Available USB Devices:\n";
foreach (var device in devicesDictionary.Values)
{
devicesInfo += $"Device Name: {device.DeviceName}, Vendor ID: {device.VendorId}, Product ID: {device.ProductId}\n";
}
DisplayAlert("USB Devices", devicesInfo, "OK");
}
else
{
DisplayAlert("USB Devices", "No USB devices available.", "OK");
}
#endif
}
}
}
The code shows the connected USB devices, but I need to be able to read incoming data from a serial port (like ), not just show device info./dev/ttyUSB0
So my questions are:
How can I initialize and read data from a Serial Port using .NET MAUI on Android?
I’d really appreciate any help or even just a code example on how to read from a serial port in an Android MAUI app.
Thanks a lot in advance!
1 answer
Sort by: Most helpful
-
Graham McKechnie 396 Reputation points
2024-09-29T00:17:20.6833333+00:00