How to read data from Serial Ports on Android using MAUI

Yusuf 20 Reputation points
2024-09-28T13:43:25.7+00:00

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!

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,346 questions
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,454 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Graham McKechnie 396 Reputation points
    2024-09-29T00:17:20.6833333+00:00

    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?

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.