Xamrin.Android蓝牙配对

问题描述 投票:0回答:1

我正在开发一个Xamarin.Android项目,我需要扫描附近的蓝牙设备,选择一个后,将它与我的设备配对。这是我到目前为止所做的:

AndroidManifest.xml中

  <uses-permission android:name="android.permission.BLUETOOTH" />
  <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

BluetoothDeviceReceiver.cs

public class BluetoothDeviceReceiver : BroadcastReceiver
{
    private static BluetoothDeviceReceiver _instance;
    public static BluetoothDeviceReceiver Receiver => _instance ?? (_instance = new BluetoothDeviceReceiver());

    public override void OnReceive(Context context, Intent intent)
    {
        var action = intent.Action;

        if (action != BluetoothDevice.ActionFound)
        {
            return;
        }

        // Get the device
        var device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
    }
}

MainScreenView.cs

protected override void OnResume()
    {
        base.OnResume();
        RegisterReceiver(BluetoothDeviceReceiver.Receiver, new IntentFilter(BluetoothDevice.ActionFound));
    }

    protected override void OnPause()
    {
        base.OnPause();
        UnregisterReceiver(BluetoothDeviceReceiver.Receiver);
    }

按钮命令:

BluetoothAdapter.DefaultAdapter.StartDiscovery();

我在OnReceive方法中放置了一个断点,但它从未到达那里。

我在这里错过了什么?

UPDATE

我工作的设备有Android 8.0.0版本。它不仅适用于该设备。当切换到不同的Android版本时,相同的解决方案工作正常。我需要找出它为什么会发生

c# bluetooth xamarin.android pairing
1个回答
1
投票

对于Android 6及更高版本,您还需要在运行时请求ACCESS_FINE_LOCATION和ACCESS_COARSE_LOCATION权限。请参考RuntimePermissions

或者你可以使用nugetpackage Plugin.Permissions来请求运行时权限(Permission.Location)参考Plugin.Permissions

获取运行时权限后:

  BluetoothManager bluetoothManager = (BluetoothManager)GetSystemService(Context.BluetoothService);
  BluetoothAdapter mBluetoothAdapter = bluetoothManager.Adapter;                   
      if (!mBluetoothAdapter.IsEnabled)
         {
           Intent enableBtIntent = new Intent(BluetoothAdapter.ActionRequestEnable);
           StartActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
         }
      else
         {
           mBluetoothAdapter.StartDiscovery();
         }


  protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        // User chose not to enable Bluetooth.
        if (requestCode == REQUEST_ENABLE_BT && resultCode == Result.Canceled)
        {
            Finish();
            return;
        }

        base.OnActivityResult(requestCode, resultCode, data);
    }
© www.soinside.com 2019 - 2024. All rights reserved.