Pregunta

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

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

¿Fue útil?

Solución

Añadir bluetooth permiso para su AndroidManifest,

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

A continuación, utilice filtros intención de escuchar la ACTION_ACL_CONNECTED, ACTION_ACL_DISCONNECT_REQUESTED y transmisiones 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 manera de recuperar una lista de dispositivos conectados al iniciarse la aplicación. La API de Bluetooth no le permite a la consulta, sino que le permite escuchar a los cambios.
  • Una obra hoaky en torno al problema anterior sería la de recuperar la lista de todos los dispositivos conocidos / pareados ... luego tratar de conectarse a cada uno (para determinar si está conectado).
  • Como alternativa, podría tener un servicio en segundo plano ver la API de Bluetooth y escribir los estados del dispositivo en el disco para su aplicación al uso en una fecha posterior.

Otros consejos

En mi caso de uso Sólo quería ver si un auricular Bluetooth está conectado a una aplicación de VoIP. La siguiente solución que 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, usted necesitará el permiso de Bluetooth:

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

Muchas gracias a Skylarsutton para su respuesta. Estoy poniendo esto como una respuesta a la suya, sino porque estoy código de anuncio no puedo responder como un comentario. Ya upvoted su respuesta por lo que no busco ningún punto. Sólo el pago hacia adelante.

Por alguna razón BluetoothAdapter.ACTION_ACL_CONNECTED no se pudo resolver por Android Studio. Tal vez está desfasada y en Android 4.2.2? Aquí es una modificación de su código. El código de registro es el mismo; el código del receptor cambia ligeramente. Utilizo este en un servicio que actualiza una bandera Bluetooth-conectado que otras partes de la referencia de aplicación.

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

Este código es para los perfiles de auricular, probablemente va a trabajar para otros perfiles también. Lo primero que necesita para proporcionar el perfil oyente (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
        }
    }
}

A continuación, durante la comprobación de Bluetooth:

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

Se necesita un poco de tiempo hasta que onSeviceConnected se llama. Después de que usted puede obtener la lista de los dispositivos auriculares conectados en:

mBluetoothHeadset!!.connectedDevices

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

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

audioManager.isBluetoothScoOn -> retornos cierto cuando dispositivo conectado

Sé que este hilo es un poco viejo, pero realmente necesitaba saber si un dispositivo se conecta a la derecha en el inicio de mi aplicación, y he encontrado la solución!

//List of Paired Devices
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();

if (pairedDevices.size() > 0) {
// There are paired devices. Get the name and address of each paired device.

    for (BluetoothDevice device : pairedDevices) {
        String deviceName = device.getName();
        String deviceHardwareAddress = device.getAddress(); // MAC address
    }
}
else {
//There are no paired devices.
}

Está disponible aquí, en Kotlin así: https: // developer.android.com/guide/topics/connectivity/bluetooth#QueryPairedDevices

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top