I am trying to check when my device is connected with a car. I assume the car acts like a bluetooth headset, therefore I have used the following code in my activity onCreate:
// Get the default adapter
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
if (profile == BluetoothProfile.HEADSET) {
mBluetoothHeadset = (BluetoothHeadset) proxy;
LogginUtil.logString("BluetoothApp", "Headset event called at " + today.format("%k:%M:%S") + " - " + profile);
} else {
LogginUtil.logString("BluetoothApp", "Other event called at " + today.format("%k:%M:%S") + " - " + profile);
}
}
public void onServiceDisconnected(int profile) {
if (profile == BluetoothProfile.HEADSET) {
mBluetoothHeadset = null;
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
LogginUtil.logString("BluetoothApp", "Headset event disconnected at " + today.format("%k:%M:%S"));
}
}
};
// Establish connection to the proxy.
mBluetoothAdapter.getProfileProxy(getApplicationContext(), mProfileListener, BluetoothProfile.HEADSET);
When I start the application, with bluetooth on and off, I get the following output:
Headset event called at "current time" - 1
When I pair my device with the car I get exactly the same output:
Headset event called at "current time" - 1
What do I need to do to detect that my device is actively connected via bluetooth with the car?
Thank you in advance, and let mw know if you require anything else.
EDIT CLARIFICATION
Just in case my question in misunderstood. I want to get notified (just a log) when the device goes into the state of being connected to a car via bluetooth. Is something like this possible?
If your Bluetooth devices won't connect, it's likely because the devices are out of range, or aren't in pairing mode. If you're having persistent Bluetooth connection problems, try resetting your devices, or having your phone or tablet "forget" the connection.
I'm not able to try it right now, but perhaps this could work:
int[] validStates = {BluetoothHeadset.STATE_AUDIO_CONNECTED};
List<BluetoothDevice> mConnectedDevices =
mBluetoothHeadset.getDevicesMatchingConnectionStates(validStates);
if (!mConnectedDevices.isEmpty()) {
// You've got something connected here
}
Sources:
http://developer.android.com/reference/android/bluetooth/BluetoothHeadset.html http://developer.android.com/reference/android/bluetooth/BluetoothProfile.html#getConnectedDevices()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With