Reputation: 676
I am creating an app where I need to display the name of connected bluetooth headset . My headset is switched on and connected to android device . I am routing phone audio to headset , but I am unable to display the connected headset name .
I tried with " getName () " method , but it returns another paired bluetooth mobile device which is not currently connected and switched off .
Need suggestions so badly .
UPDATE
I used this code . But unfortunately it returns an android bluetooth device name which is not currently connected , where my headset is still connected and I am able to route phone audio
bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.cancelDiscovery();
Set<BluetoothDevice> getDevices = bluetoothAdapter.getBondedDevices();
String remoteDevice = null;
for (BluetoothDevice getDevice : getDevices) {
//stringBuilder.append(getDevice);
remoteDevice = getDevice.toString();
}
blueToothDevice = bluetoothAdapter.getRemoteDevice(remoteDevice);
StringBuilder stringBuilder1 = new StringBuilder();
stringBuilder1.append(blueToothDevice.getName());
Upvotes: 1
Views: 3846
Reputation: 676
I finally solved the problem . Previously I got all bonded devices with " getBondedDevices() " method from " BluetoothAdpter " class . But I fixed the problem by using "getConnectedDevices" method from the class " BluetoothProfile ".
My new code is below, which only shows the connected bluetooth headset device name which only connected to HEADSET profile .
bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.cancelDiscovery();
bluetoothAdapter.getProfileProxy(this, listener, BluetoothProfile.HEADSET);
public final BluetoothProfile.ServiceListener listener = new BluetoothProfile.ServiceListener() {
@Override
public void onServiceConnected(int i, final BluetoothProfile bluetoothProfile) {
final TextView txt = (TextView) findViewById(R.id.textView);
List<BluetoothDevice> b = bluetoothProfile.getConnectedDevices();
StringBuilder stringBuilder = new StringBuilder();
for(BluetoothDevice getConnectedDevice : b){
stringBuilder.append(getConnectedDevice.getName());
}
txt.setText(stringBuilder);
}
@Override
public void onServiceDisconnected(int i) {
final TextView txt = (TextView) findViewById(R.id.textView);
txt.setText(String.valueOf(i));
}
};
Upvotes: 2