How to get bluetooth connected devices using BluetoothHeadset API
Finally got the solution. Below are a few code snippets for getting Bluetooth audio connected devices using BluetoothHeadset
API.
BluetoothHeadset mBluetoothHeadset;
// Get the default adapter
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// Establish connection to the proxy.
mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET);
// Define Service Listener of BluetoothProfile
private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == BluetoothProfile.HEADSET) {
mBluetoothHeadset = (BluetoothHeadset) proxy;
}
}
public void onServiceDisconnected(int profile) {
if (profile == BluetoothProfile.HEADSET) {
mBluetoothHeadset = null;
}
}
};
// call functions on mBluetoothHeadset to check if Bluetooth SCO audio is connected.
List<BluetoothDevice> devices = mBluetoothHeadset.getConnectedDevices();
for ( final BluetoothDevice dev : devices ) {
return mBluetoothHeadset.isAudioConnected(dev);
}
// finally Close proxy connection after use.
mBluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, mBluetoothHeadset);
Programmatically connect to bluetooth headset from android app
First of All, you need to make sure Bluetooth is Enabled then Search for Unpaired Devices, Then Using Device Address, You pair the Device.
After Successful Pairing, you will need to connect to the device and Also HSP or HFP profiles.
Note without HSP(Headset Profile) or HFP(Hands-Free Profile) you won't be able to connect and stream calls to your Headset or Speaker.
I laid down the steps for you can easily find more details by googling each step.
Hopefully, this helps you.
UPDATE
I will try and help you a bit more :
you have to add a new package under the "src" folder with name: android.bluetooth
then create IBluetoothHeadset.aidl
with the following code:
package android.bluetooth;
import android.bluetooth.BluetoothDevice;
interface IBluetoothHeadset {
// Public API
boolean connect(in BluetoothDevice device); //Api 11 and above
boolean connectHeadset(in BluetoothDevice device); // Below Api 11
boolean disconnect(in BluetoothDevice device);
boolean disconnectHeadset(in BluetoothDevice device);
List<BluetoothDevice> getConnectedDevices();
List<BluetoothDevice> getDevicesMatchingConnectionStates(in int[] states);
int getConnectionState(in BluetoothDevice device);
int getState(in BluetoothDevice device);
boolean setPriority(in BluetoothDevice device, int priority);
int getPriority(in BluetoothDevice device);
boolean startVoiceRecognition(in BluetoothDevice device);
boolean stopVoiceRecognition(in BluetoothDevice device);
boolean isAudioConnected(in BluetoothDevice device);
boolean sendVendorSpecificResultCode(in BluetoothDevice device,
in String command,
in String arg);
// APIs that can be made public in future
int getBatteryUsageHint(in BluetoothDevice device);
// Internal functions, not be made public
boolean acceptIncomingConnect(in BluetoothDevice device);
boolean rejectIncomingConnect(in BluetoothDevice device);
int getAudioState(in BluetoothDevice device);
boolean isAudioOn();
boolean connectAudio();
boolean disconnectAudio();
boolean startScoUsingVirtualVoiceCall(in BluetoothDevice device);
boolean stopScoUsingVirtualVoiceCall(in BluetoothDevice device);
void phoneStateChanged(int numActive, int numHeld, int callState, String number, int type);
void clccResponse(int index, int direction, int status, int mode, boolean mpty,
String number, int type);
}
Then in your activity
BluetoothDevice DeviceToConnect;
IBluetoothHeadset ibth;
//IBluetoothHeadset instance used to connect and disconnect headset afterwards
// Create and Register BroadCastListener for Action "HEADSET_INTERFACE_CONNECTED"
// In Broadcast your code has to be something like that
// if(ibth != null) ibth.connect(DeviceToConnect);
//Then After Pairing DeviceToConnect;
Intent i = new Intent(IBluetoothHeadset.class.getName());
if (bindService(i, HSPConnection, Context.BIND_AUTO_CREATE)) {
} else {
Log.e("HSP FAILED", "Could not bind to Bluetooth HFP Service");
}
//Method for bind
public static ServiceConnection HSPConnection= new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
ibth = IBluetoothHeadset.Stub.asInterface(service);
//ibth instance used to connect and disconnect headset afterwards
Intent intent = new Intent();
intent.setAction("HEADSET_INTERFACE_CONNECTED");
//same as the one we register earlier for broadcastreciever
ctx.sendBroadcast(intent);
//ctx is Instance of Context
}
@Override
public void onServiceDisconnected(ComponentName name) {
ibth=null;
}
};
UPDATE 2:
<intent-filter>
<action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
</intent-filter>
These are the filters you have to add to your broad cast receiver.
ACL_CONNECTED signals when bluetooth is connected and ACL_DISCONNECTED signals bluetooth disconnection
For specific device you have to check intents/context in broadcast receiver
So your new Receiver including the previous will look something like that:
BroadcastReceiver bcr = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//Device found
}
else if (BluetoothAdapter.ACTION_ACL_CONNECTED.equals(action)) {
//Device is now connected
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//Done searching
}
else if (BluetoothAdapter.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
//Device is about to disconnect
}
else if (BluetoothAdapter.ACTION_ACL_DISCONNECTED.equals(action)) {
//Device has disconnected add whatever way u want to be notified here
//e.g music-vibration-screen light
}else if("HEADSET_INTERFACE_CONNECTED".equals(action){
if(ibth != null) ibth.connect(DeviceToConnect);
}
}
};
I forgot to add that you need these 2 permissions in Manifest:
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
How can I programmatically tell if a Bluetooth device is connected?
Add the Bluetooth permission to your AndroidManifest,
<uses-permission android:name="android.permission.BLUETOOTH" />
Then use intent filters to listen to the ACTION_ACL_CONNECTED
, ACTION_ACL_DISCONNECT_REQUESTED
, and ACTION_ACL_DISCONNECTED
broadcasts:
public void onCreate() {
...
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter);
}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
... //Device found
}
else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
... //Device is now connected
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
... //Done searching
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
... //Device is about to disconnect
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
... //Device has disconnected
}
}
};
A few notes:
- There is no way to retrieve a list of connected devices at application startup. The Bluetooth API does not allow you to query, instead it allows you to listen to changes.
- A hoaky workaround to the above problem would be to retrieve the list of all known/paired devices... then trying to connect to each one (to determine if you're connected).
- Alternatively, you could have a background service watch the Bluetooth API and write the device states to disk for your application to use at a later date.
Connect WP8 device to a bluetooth headset programmatically
ConnectAsync
opens a socket for the calling program to send/receive data over. That's not what you want, instead you want the OS to connect to the Headset service. In Win32 that's BluetoothSetServiceState
but I don't know an equivalent 'modern' API.
Also in Win32 one could use BluetoothAuthenticateDeviceEx
which would cause pairing, and *probably* connect the headset services -- and with full Out-Of-Band authentication if supplied by the NFC channel. Again I don't know of an equivalent.
I suppose there's a possibility that doing a ConnectAsync to an arbitrary endpoint (e.g. "15"
) will cause pairing to start which will then complete and enable the Headset service... The ConnectAsync call itself will fail but it is its side-effect we're interested in. May be worth a try.
Presumably you're getting the headset device's device address from the NFC comms? If so, you can create the HostName
object to use in the ConnectAsync
as Peter describes: http://peterfoot.net/PersistBluetoothAddressesOnWindowsPhone8.aspx
Android 2.2 progammically tell if my Bluetooth Headset is connected on application start
Unfortunately there is really no way to do this in Java on an unrooted device. If you have a device with root access and you use the NDK you can drop into the BlueZ programming layer and you can do it there, but with the publicly available Java API there is no way to do this.
Related Topics
Taking a "Screenshot" of a Specific Layout in Android
How to Get Chrome Browsing History/Bookmarks in Our Android App
In Espresso, How to Avoid Ambiguousviewmatcherexception When Multiple Views Match
Is Arm64-V8A Compatible with Armeabi-V7A
Delete File from Internal Storage
Savedinstancestate Is Always Null in Fragment
How to Create Multiple Pendingintents with the Same Requestcode and Different Extras
Viewing Excel Files in My Android App
Android Sax Parser Not Getting Full Text from Between Tags
Using the New "Manifestmerger" Property in Android
Firebase Authentication State Change Does Not Fire When User Is Disabled or Deleted
Findviewbyid Returns Null When Using Fragment
How to Use Tabhost.Ontabchangelistener in Android
Java.Io.Ioexception: Unexpected End of Stream on Connection in Android