How to determine if a Bluetooth device is connected

In android, how can my activity find out if a Bluetooth A2DP device is connected to my device.
Is there a radio transmitter for this?
How to record this broadcast receiver?

+3
source share
5 answers

Starting with API 11 (Android 3.0), you can use the BluetoothAdapter to discover devices connected to a specific Bluetooth profile. I used the code below to find the device by its name:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
        public void onServiceConnected(int profile, BluetoothProfile proxy) {
            if (profile == BluetoothProfile.A2DP) {
                boolean deviceConnected = false;
                BluetoothA2dp btA2dp = (BluetoothA2dp) proxy;
                List<BluetoothDevice> a2dpConnectedDevices = btA2dp.getConnectedDevices();
                if (a2dpConnectedDevices.size() != 0) {
                    for (BluetoothDevice device : a2dpConnectedDevices) {
                        if (device.getName().contains("DEVICE_NAME")) {
                            deviceConnected = true;
                        }
                    }
                }
                if (!deviceConnected) {
                    Toast.makeText(getActivity(), "DEVICE NOT CONNECTED", Toast.LENGTH_SHORT).show();
                }
                mBluetoothAdapter.closeProfileProxy(BluetoothProfile.A2DP, btA2dp);
            }
        }

        public void onServiceDisconnected(int profile) {
            // TODO
        }
    };
mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.A2DP);

You can do this for each Bluetooth profile. Take a look at Working with profiles in the Android manual.

, , BroadcastReceiver (, android < 3.0).

+10

, API. ACTION_ACL_CONNECTED, ACTION_ACL_DISCONNECTED, . .

, ( ...), / Bluetooth , , .

+9

; fetchUUIDsWithSDP() , ... , , UUID () , . .

+1
0

...

// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    // When discovery finds a device
    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        // Get the BluetoothDevice object from the Intent
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        // Add the name and address to an array adapter to show in a ListView
        mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
    }
}

};

 // Register the BroadcastReceiver

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
-1

Source: https://habr.com/ru/post/1782402/


All Articles