我正在尝试使用A2DP配置文件控制与设备的蓝牙连接。
在Android的原生Java开发中,开发人员使用BluetoothA2dp类建立连接。
Xamarin也有一个同名的类 - BluetoothA2dp。但是由于它没有构造函数,我似乎无法理解如何初始化它的实例。
如何借助该类端口创建连接?
我正在尝试使用A2DP配置文件控制与设备的蓝牙连接。
在Android的原生Java开发中,开发人员使用BluetoothA2dp类建立连接。
Xamarin也有一个同名的类 - BluetoothA2dp。但是由于它没有构造函数,我似乎无法理解如何初始化它的实例。
如何借助该类端口创建连接?
您不需要直接使用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)
{
}
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文档,在这里参考。
GetConnectionState
,因为它不是一个抽象或虚方法,而且这个类也是密封的,所以不能被继承。另外,上面的MyClassExtender
是一个静态类,所以不能像你建议的那样实例化。上面的语法是用来创建一个扩展方法到BluetoothA2DP
类的,你需要一个实例。请看我的答案,了解如何访问A2DP代理对象。 - Tom Bowers
OnServiceConnected
,但是当我们从系统蓝牙连接活动手动连接A2DP配置文件(到远程设备)时,事件没有被触发。理论上,什么时候应该执行OnServiceConnected
方法? - Maxim V. PavlovOnServiceConnected
方法,而不是在设备连接时调用。因此,在调用GetProfileProxy
后不久,它将被调用。我已经使用上面发布的代码测试了一个快速活动,并按预期调用了该方法。我需要看一些代码才能给出建议。 - Tom Bowers