How to read data from Serial Ports on Android using MAUI

Yusuf-3141 25 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!

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,469 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Graham McKechnie 406 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?

    1 person found this answer helpful.

  2. A SIVAGAYATHRI 0 Reputation points
    2024-09-29T13:08:43.7333333+00:00

    In .NET MAUI for Android, you can use the Android Hardware APIs to work with serial ports since .NET MAUI itself doesn't have direct serial port support.

    Here’s a brief approach:

    1. Use Android Java APIs (UsbManager and UsbDevice) to access the serial ports.
    2. Implement serial communication using the UsbSerial for Android library or other external libraries.
    3. Call these Android-specific APIs in your MAUI app using platform-specific code.

    You'd need to write platform-specific code under the Platforms/Android folder to handle this.


  3. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 75,121 Reputation points Microsoft Vendor
    2024-10-02T09:39:43.95+00:00

    Hello,

    You can read data from the UsbEndpoint using use UsbDeviceConnection.bulkTransfer. This method is blocking, please use it in a thread.

    Then you can open the device using UsbManager and UsbDeviceConnection. Then read it.

    UsbInterface usbInterface = device.getInterface(0);  // Get the interface of the device
      UsbEndpoint endpointIn = usbInterface.GetEndpoint(0); // Assuming the first endpoint is IN
      UsbDeviceConnection connection = UsbManager.OpenDevice(device); // Open connection
     
      if (connection != null && connection.ClaimInterface(usbInterface, true))
      {
          // Connection successful
     
          int TIMEOUT = 1000;  // Timeout for reading
          byte[] buffer = new byte[64];  // Buffer for reading data
          int readBytes = connection.BulkTransfer(endpointIn, buffer, buffer.Length, TIMEOUT);
     
          if (readBytes > 0)
          {
              Java.Lang.String data = new Java.Lang.String(buffer, 0, readBytes);
              Log.Debug("USB", "Read data: " + data.ToString());
          }
      }
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    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.