Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to find out name of the bluetooth device connected?

Basically im trying 2 things here, Im trying to start a toast when my bluetooth device is connected to a particular device (so need to check if that is the particular bluetooth name), if that is the particular device then i want to show a toast when connected to that particular bluetooth device. I also want to show a toast when my bluetooth is disconnected to that particular bluetooth device. Here's my code: in manifest.xml

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

<receiver android:name=".MyBluetoothReceiver" >
    <intent-filter>
    <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
    <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
    <action android:name="android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED" />           
</intent-filter>  
</receiver>  

Class's code:

public class MyBluetoothReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

         Toast.makeText(context, "RECEIVER CALLED!!", Toast.LENGTH_LONG).show();


        if(intent.getAction().equals(
          "android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED")){

           // code for Bluetooth connect

           Toast.makeText(context, "CONNECTED!!", Toast.LENGTH_LONG).show();
        }

        if(intent.getAction().equals(
          "android.bluetooth.device.action.ACL_DISCONNECTED")){

          //code for Bluetooth disconnect;
          Toast.makeText(getApplicationContext(),"DISCONNECTED",Toast.LENGTH_LONG).show();
        }
    }
}

In my code im getting receiver called toast properly and even the toast for disconnected is also working but toast of connected never works.

Please let me know why CONNECTED toast doesn't work and how to make this code work when connected to a particular device ( I don't want to show this toast for all the devices ).

like image 819
Siddharth Sachdeva Avatar asked Jan 12 '14 09:01

Siddharth Sachdeva


1 Answers

Change your broadcast receiver to:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        // When discovery finds a device
        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent
                    .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                          //you can get name by device.getName()

        } else if (BluetoothAdapter.ACL_DISCONNECTED
                .equals(action)) {

        }
    }
 };
like image 89
vipul mittal Avatar answered Oct 16 '22 07:10

vipul mittal