¿Cómo saber mediante programación si un dispositivo Bluetooth está conectado? (Android 2.2)


Entiendo cómo obtener una lista de dispositivos emparejados, pero ¿cómo puedo saber si están conectados?

Debe ser posible ya que los veo listados en la lista de dispositivos Bluetooth de mi teléfono y establece su estado de conexión.

Author: Vadim Kotov, 2011-01-17

5 answers

Use filtros de intent para escuchar las transmisiones ACTION_ACL_CONNECTED, ACTION_ACL_DISCONNECT_REQUESTED y ACTION_ACL_DISCONNECTED:

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
        }           
    }
};

Algunas notas:

  • No hay forma de recuperar una lista de dispositivos conectados al inicio de la aplicación. La API de Bluetooth no le permite realizar CONSULTAS, sino que le permite escuchar los CAMBIOS.
  • Un trabajo raro en torno al problema anterior sería recuperar la lista de todos los dispositivos conocidos/emparejados... a continuación, tratando de conectarse a cada uno (para determinar si estás conectado).
  • Alternativamente, puede hacer que un servicio en segundo plano observe la API de Bluetooth y escriba los estados del dispositivo en el disco para que su aplicación los use en una fecha posterior.
 122
Author: Skylar Sutton,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-23 13:47:40

En mi caso de uso solo quería ver si un auricular Bluetooth está conectado para una aplicación VoIP. La siguiente solución funcionó para mí:

public static boolean isBluetoothHeadsetConnected() {
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    return mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()
            && mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_CONNECTED;
} 

Por supuesto, necesitarás el permiso Bluetooth:

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

 17
Author: jobbert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-16 09:47:57

Muchas gracias a Skylarsutton por su respuesta. Estoy publicando esto como una respuesta a la suya, pero porque estoy publicando código no puedo responder como un comentario. Ya voté a favor de su respuesta, así que no estoy buscando ningún punto. Sólo pagándolo.

Por alguna razón BluetoothAdapter.ACTION_ACL_CONNECTED no pudo ser resuelto por Android Studio. Tal vez fue obsoleto en Android 4.2.2? Aquí hay una modificación de su código. El código de registro es el mismo; el código del receptor difiere ligeramente. Yo uso esto en un servicio que actualiza un indicador conectado a Bluetooth que otras partes de la aplicación hacen referencia.

    public void onCreate() {
        //...
        IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
        IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
        IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        this.registerReceiver(mReceiver, filter1);
        this.registerReceiver(mReceiver, filter2);
        this.registerReceiver(mReceiver, filter3);
    }

    //The BroadcastReceiver that listens for bluetooth broadcasts
    private final BroadcastReceiver BTReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            //Do something if connected
            Toast.makeText(getApplicationContext(), "BT Connected", Toast.LENGTH_SHORT).show();
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
            //Do something if disconnected
            Toast.makeText(getApplicationContext(), "BT Disconnected", Toast.LENGTH_SHORT).show();
        }
        //else if...
    }
};
 9
Author: pmont,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-02 02:53:35

BluetoothAdapter.getDefaultAdapter().isEnabled -> devuelve true cuando bluetooth está abierto

val audioManager = this.getSystemService(Context.AUDIO_SERVICE) as AudioManager

audioManager.isBluetoothScoOn -> devuelve true cuando el dispositivo está conectado

 0
Author: ravid rinek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-05 11:31:57

Este código es para los perfiles de auriculares, probablemente también funcionará para otros perfiles. Primero debe proporcionar el listener de perfil (código Kotlin):

private val mProfileListener = object : BluetoothProfile.ServiceListener {
    override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
        if (profile == BluetoothProfile.HEADSET) 
            mBluetoothHeadset = proxy as BluetoothHeadset            
    }

    override fun onServiceDisconnected(profile: Int) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = null
        }
    }
}

Luego, mientras comprueba bluetooth:

mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET)
if (!mBluetoothAdapter.isEnabled) {
    return Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
}

Toma un poco de tiempo hasta que se llame a oneviceconnected. Después de eso, puede obtener la lista de los dispositivos de auriculares conectados de:

mBluetoothHeadset!!.connectedDevices
 0
Author: hesy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-11 14:02:22