We need our application to be able to connect to a paired bluetooth device automatically when an application starts via A2DP or Hands Free Profile.
We are working in Xamarin (monodroid), for Android platform.
I've found this stackoverflow question: Programmatically connect to paired Bluetooth device
But it relates to native ways of achieving this (see answer by kcoppock). I'd like to know if there is a way to achieve this via Xamarin. We can connect to SPP endpoint since it's an RFCOMM based connection, but we need that and the audio connection, so we are loking for a way to connect to A2DP.
Update 1:
We have tried to connect using CreateInsecureRfcommSocketToServiceRecord
method like this:
mmSocket = device.CreateInsecureRfcommSocketToServiceRecord(0000110A-0000-1000-8000-00805F9B34FB);
mmSocket.Connect();
Upon a call to Connect, we are getting an error:
read failed, socket might closed or timeout, read ret: -1
Stack trace begins with:
Java.IO.IOException at Android.Runtime.JNIEnv.CallVoidMethod (IntPtr jobject, IntPtr jmethod) [0x00062] in /Users/buil…
Update 2:
By the way, whene we try to connect via the native java test app using the approach by kcoppock, the connection code seems to work without an error, although the device isn't being connected as an A2DP headset.
The only programming way we have seen to be able to do it was this Google Play app, which proves that it is possible.
Remember that Xamarin binds to native api so don't worry that something "relates to native ways" ;) Based on the anwser You referenced I wrote and tested the code below. I hope it will help You.
class btListener : Java.Lang.Object, IBluetoothProfileServiceListener
{
public void OnServiceConnected([GeneratedEnum] ProfileType profile, IBluetoothProfile proxy)
{
String deviceName = "JABRA WAVE+";
BluetoothDevice result = null;
var devices = BluetoothAdapter.DefaultAdapter.BondedDevices;
if (devices != null)
{
foreach (BluetoothDevice device in devices)
{
if (deviceName == device.Name)
{
result = device;
break;
}
}
}
var connect = Java.Lang.Class.FromType(typeof(BluetoothA2dp)).GetDeclaredMethod("connect", Java.Lang.Class.FromType(typeof(BluetoothDevice)));
connect.Invoke((Java.Lang.Object)proxy, result);
}
public void OnServiceDisconnected([GeneratedEnum] ProfileType profile)
{
}
}
Following code in e.g. OnCreate function:
btListener btReceiver = new btListener();
BluetoothAdapter.DefaultAdapter.GetProfileProxy(this, btReceiver, ProfileType.A2dp);
Just looked at the date.. but I'm posting answer anyway - maybe it's still going to help somebody