Xamrin.Android蓝牙配对

时间:2019-02-20 10:01:56

标签: c# bluetooth xamarin.android pairing

我正在研究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方法中放置了一个断点,但从未到达那里。

我在这里想念什么?

更新

我使用的设备具有Android 8.0.0版本。它不仅在该设备上起作用。切换到其他Android版本时,相同的解决方案效果很好。我需要找出为什么会发生

1 个答案:

答案 0 :(得分: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);
    }