You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Xamarin手机应用中添加Bluetooth-LowEnergy服务与可写特征

Hey there! Let me walk you through how to add a Bluetooth Low Energy (BLE) service and writable characteristic to your Xamarin app—whether you prefer a cross-platform library to keep things consistent across iOS and Android, or need to go native for more control, I’ve got you covered.

1. Cross-Platform Approach with Plugin.BLE

This is the most straightforward way to handle BLE in Xamarin, as it abstracts away most platform-specific details. Here’s how to set up your service and writable characteristic:

Step 1: Install the Library

First, add the Plugin.BLE NuGet package to your Xamarin.Forms project (and platform projects if needed).

Step 2: Create a Service and Writable Characteristic

You’ll need to define your service UUID and characteristic UUID first—make sure they’re valid 128-bit UUIDs (or use pre-defined 16-bit ones if applicable).

using Plugin.BLE.Server;
using Plugin.BLE.Abstractions.Contracts;
using Plugin.BLE.Abstractions.Attributes;

// Define your custom service with a unique UUID
[Service(UUID = "YOUR_CUSTOM_SERVICE_UUID")]
public class CustomBleService : ServiceBase
{
    // Define a writable characteristic with appropriate properties
    [Characteristic(UUID = "YOUR_WRITABLE_CHAR_UUID", 
                    Properties = CharacteristicProperties.Write | CharacteristicProperties.WriteWithoutResponse,
                    Permissions = CharacteristicPermissions.Write)]
    public byte[] WritableCharacteristic { get; set; }

    // Optional: Handle incoming write events from clients
    public override void OnCharacteristicWrite(ICharacteristic characteristic, byte[] value)
    {
        base.OnCharacteristicWrite(characteristic, value);
        // Process the received data here (e.g., convert to string, trigger app logic)
        var receivedText = System.Text.Encoding.UTF8.GetString(value);
        Console.WriteLine($"Received data from client: {receivedText}");
    }
}

Step 3: Start Advertising the Service

In your platform-specific code (or a shared service using dependency injection), initialize the BLE server and start broadcasting your service:

// Initialize BLE server and add your custom service
var bleServer = CrossBluetoothLE.Current.Server;
var customService = new CustomBleService();
await bleServer.AddServiceAsync(customService);

// Start advertising with a recognizable device name
await bleServer.StartAdvertisingAsync(new AdvertisementData { LocalName = "MyXamarinBLEDevice" });
2. Native Implementation (For Full Control)

If you need to leverage platform-native APIs directly, here’s a quick breakdown for each OS:

Android

Android uses BluetoothGattService and BluetoothGattCharacteristic classes. Here’s a snippet to create and register a writable characteristic:

using Android.Bluetooth;

// Get Bluetooth adapter from system service
var bluetoothManager = (BluetoothManager)GetSystemService(BluetoothService);
var bluetoothAdapter = bluetoothManager.Adapter;

// Create service and writable characteristic
var serviceUuid = UUID.FromString("YOUR_SERVICE_UUID");
var charUuid = UUID.FromString("YOUR_WRITABLE_CHAR_UUID");

var gattService = new BluetoothGattService(serviceUuid, GattServiceType.Primary);
var writableChar = new BluetoothGattCharacteristic(
    charUuid, 
    GattProperty.Write | GattProperty.WriteNoResponse, 
    GattPermission.Write);

gattService.AddCharacteristic(writableChar);

// Open GATT server and add the service
var gattServer = bluetoothAdapter.OpenGattServer(this, new CustomGattServerCallback());
gattServer.AddService(gattService);

// Custom callback to handle write requests
public class CustomGattServerCallback : GattServerCallback
{
    public override void OnCharacteristicWriteRequest(BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic, bool preparedWrite, bool responseNeeded, int offset, byte[] value)
    {
        base.OnCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value);
        
        // Process incoming data
        var receivedData = System.Text.Encoding.UTF8.GetString(value);
        // Send success response if required
        gattServer.SendResponse(device, requestId, GattStatus.Success, offset, null);
    }
}

iOS

iOS uses CBMutableService and CBMutableCharacteristic for mutable (writable) BLE components:

using CoreBluetooth;

// Create mutable service and characteristic
var serviceUuid = CBUUID.FromString("YOUR_SERVICE_UUID");
var charUuid = CBUUID.FromString("YOUR_WRITABLE_CHAR_UUID");

var mutableService = new CBMutableService(serviceUuid, true);
var mutableChar = new CBMutableCharacteristic(
    charUuid, 
    CBCharacteristicProperties.Write | CBCharacteristicProperties.WriteWithoutResponse, 
    null, 
    CBAttributePermissions.Writeable);

mutableService.Characteristics = new CBCharacteristic[] { mutableChar };

// Initialize peripheral manager and start advertising
var peripheralManager = new CBPeripheralManager(new CustomPeripheralDelegate());
peripheralManager.AddService(mutableService);

var advertisementData = new CBAdvertisementData { LocalName = "MyXamarinBLEDevice" };
peripheralManager.StartAdvertising(advertisementData);

// Custom delegate to handle write requests
public class CustomPeripheralDelegate : CBPeripheralManagerDelegate
{
    public override void DidReceiveWriteRequests(CBPeripheralManager peripheral, CBATTRequest[] requests)
    {
        base.DidReceiveWriteRequests(peripheral, requests);
        foreach (var request in requests)
        {
            var receivedText = System.Text.Encoding.UTF8.GetString(request.Value.ToArray());
            // Process the data as needed
            peripheral.RespondToRequest(request, CBATTError.Success);
        }
    }
}
3. Critical Notes to Avoid Headaches
  • Permissions: Don’t skip adding required BLE permissions:
    • Android: Add BLUETOOTH, BLUETOOTH_ADVERTISE, BLUETOOTH_CONNECT (and ACCESS_FINE_LOCATION for older API levels) to AndroidManifest.xml.
    • iOS: Add NSBluetoothAlwaysUsageDescription and NSBluetoothPeripheralUsageDescription to Info.plist with clear usage messages.
  • UUID Validity: Use unique 128-bit UUIDs for custom services/characteristics (you can generate one easily online).
  • Error Handling: Always check if BLE is enabled on the device, and handle cases where the server fails to start or advertise.
  • Background Mode: If your app needs to handle BLE writes or advertise in the background, enable the BLE peripheral background mode for iOS and appropriate background permissions for Android.

内容的提问来源于stack exchange,提问作者hacene abdessamed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:20:51