Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get name of the connected Bluetooth device on android

I'm trying to get the name of the device that is connected to the Android phone running android Oreo.

I was searching for an answer for the past two days, and none of them worked. suggestions mostly returning ioexception-read-failed-socket-might-closed-bluetooth error

The question is, is there any way to make Query that returns the connected Bluetooth device?

These are the links and suggestion which not working:

  • IOException: read failed, socket might closed - Bluetooth on Android 4.3
  • In Android, how to get the profile of a connected bluetooth device?
  • list connected bluetooth devices?

I can get information about the device that is previously paired and trying to make a connection or a device trying to pair to the device. what I want is the name or the connection state of the currently paired and connected device.

like image 385
Hossain Ehsani Avatar asked Oct 26 '25 13:10

Hossain Ehsani


2 Answers

here is the answer :

String name;
String address;
String threadName;
public void checkConnected()
{

       BluetoothAdapter.getDefaultAdapter().getProfileProxy(this, serviceListener, BluetoothProfile.HEADSET);
}

private BluetoothProfile.ServiceListener serviceListener = new BluetoothProfile.ServiceListener()
{
    @Override
    public void onServiceDisconnected(int profile)
    {

    }

    @Override
    public void onServiceConnected(int profile, BluetoothProfile proxy)
    {

        for (BluetoothDevice device : proxy.getConnectedDevices())
        {
            name = device.getName();
            address = device.getAddress();
            threadName = Thread.currentThread().getName();
            Toast.makeText(MainActivity.this, name+" " + address+ threadName,  Toast.LENGTH_SHORT).show();
            txtName.setText(name + " " + address);
            Log.i("onServiceConnected", "|" + device.getName() + " | " + device.getAddress() + " | " + proxy.getConnectionState(device) + "(connected = "
                    + BluetoothProfile.STATE_CONNECTED + ")");
        }

        BluetoothAdapter.getDefaultAdapter().closeProfileProxy(profile, proxy);
    }
};
like image 174
Hossain Ehsani Avatar answered Oct 29 '25 02:10

Hossain Ehsani


Have you tried this?

BluetoothServerSocket bluetoothServerSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord("abc", uuid);          
BluetoothSocket bluetoothSocket = bluetoothServerSocket.accept();
BluetoothDevice device = bluetoothSocket.getRemoteDevice();
String deviceName = device.getName();
like image 33
rbdk Avatar answered Oct 29 '25 01:10

rbdk