如何在Xamarin中使用BluetoothA2dp类

6

我正在尝试使用A2DP配置文件控制与设备的蓝牙连接。

在Android的原生Java开发中,开发人员使用BluetoothA2dp类建立连接。

Xamarin也有一个同名的类 - BluetoothA2dp。但是由于它没有构造函数,我似乎无法理解如何初始化它的实例。

如何借助该类端口创建连接?

2个回答

2

您不需要直接使用BluetoothA2dp类。根据Android文档...

BluetoothA2dp是一个代理对象,通过IPC控制蓝牙A2DP服务。使用getProfileProxy(Context, BluetoothProfile.ServiceListener, int)获取BluetoothA2dp代理对象。

您应该使用BluetoothAdapter.GetProfileProxy来初始化与A2DP代理对象的连接。

BluetoothAdapter.DefaultAdapter.GetProfileProxy(this, serviceListener, ProfileType.A2dp);

上述方法调用中的serviceListener参数需要是实现了IBluetoothProfileServiceListener接口的类的实例,在其中您可以通过OnServiceConnected方法访问代理对象。

public void OnServiceConnected(ProfileType profile, IBluetoothProfile proxy)
{

}

嗨,谢谢。我们已经“注册”了OnServiceConnected,但是当我们从系统蓝牙连接活动手动连接A2DP配置文件(到远程设备)时,事件没有被触发。理论上,什么时候应该执行OnServiceConnected方法? - Maxim V. Pavlov
当AD2P代理对象连接到服务时,将调用OnServiceConnected方法,而不是在设备连接时调用。因此,在调用GetProfileProxy后不久,它将被调用。我已经使用上面发布的代码测试了一个快速活动,并按预期调用了该方法。我需要看一些代码才能给出建议。 - Tom Bowers
尽管一个开发人员表示在他的机器上OnServiceConnected没有被调用,但我认为这回答了关于如何使用这个类的问题,因此我将其标记为正确的。谢谢。 - Maxim V. Pavlov

-1

Xamarin版本5.0至5.2提供了“BluetoothA2DP”类,请参考链接

由于“BluetoothA2DP”是一个密封类,因此无法继承。您只能通过其实例来使用它。

您需要重写其"GetConnectionState""GetDevicesMatchingConnectionStates"方法以连接特定设备。

可能,您最好的选择是尝试使用自己的扩展方法来扩展"BluetoothA2DP"的功能。

假设您的"BluetoothA2DP"类如下:

public sealed class BluetoothA2dp : Java.Lang.Object,   IBluetoothProfile, IDisposable {
    public ProfileState GetConnectionState (BluetoothDevice device)  {
        return some_device_configs;
    }
}

然后你自己的类继承"BluetoothA2DP"类的功能,如下:

public static class MyClassExtender
{
    public static void ExtendedTest(this BluetoothA2DP instance)
    {
        instance.GetConnectionState();        
    }
}

然后使用ExtendedTest()方法来利用"BluetoothA2DP"类。

希望这样可以工作 :)

您可以查看完整的API文档,在这里参考


嗨。谢谢。好的,我已经按照您演示的方式添加了扩展方法。如果我有一个BluetoothA2DP实例,我就可以从中调用ExtendedTest()。但是由于我没有该类的实例,因此无法使用BluetoothA2dp作为静态类访问ExtendedTest()方法。我如何正确调用ExtendedTest()方法? - Maxim V. Pavlov
你需要创建"MyClassExtender"类的实例,并通过它调用"ExtendedTest()"方法。 - Mazzu
1
这个建议是不正确的。你不能“覆盖”GetConnectionState,因为它不是一个抽象或虚方法,而且这个类也是密封的,所以不能被继承。另外,上面的MyClassExtender是一个静态类,所以不能像你建议的那样实例化。上面的语法是用来创建一个扩展方法到BluetoothA2DP类的,你需要一个实例。请看我的答案,了解如何访问A2DP代理对象。 - Tom Bowers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接