Domanda

ho capito come ottenere un elenco dei dispositivi associati, ma come faccio a sapere se sono collegati?

Deve essere possibile in quanto li vedo nella lista dei dispositivi Bluetooth del mio telefono e si afferma il loro stato di connessione.

È stato utile?

Soluzione

Aggiungi bluetooth permesso di vostro AndroidManifest,

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

Quindi utilizzare filtri intento ad ascoltare la ACTION_ACL_CONNECTED, ACTION_ACL_DISCONNECT_REQUESTED, e le trasmissioni 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
        }           
    }
};

Alcune note:

  • Non v'è alcun modo per recuperare un elenco di dispositivi collegati all'avvio dell'applicazione. L'API Bluetooth non ti permette di interrogare, invece permette di ascoltare ai cambiamenti.
  • Un lavoro hoaky intorno al problema di cui sopra potrebbe essere quella di recuperare l'elenco di tutti i dispositivi noti / accoppiati ... poi tenta di connettersi a ciascuno (per determinare se si è connessi).
  • In alternativa, si potrebbe avere un orologio servizio in background l'API Bluetooth e scrivere il dispositivo stati su disco per l'applicazione per utilizzare in un secondo momento.

Altri suggerimenti

Nel mio caso d'uso Volevo solo vedere se un auricolare Bluetooth è collegato per un'applicazione VoIP. La seguente soluzione ha funzionato per me:

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

Naturalmente sarà necessario il permesso Bluetooth:

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

Un grande grazie a Skylarsutton per la sua risposta. Sto postando questo come una risposta al suo, ma perché sono il codice distacco non posso rispondere come un commento. Ho già upvoted la sua risposta, quindi non sono alla ricerca di eventuali punti. Basta pagare in avanti.

Per qualche ragione BluetoothAdapter.ACTION_ACL_CONNECTED non può essere risolto da Android Studio. Forse è stata sconsigliata a Android 4.2.2? Qui è una modifica del suo codice. Il codice di registrazione è lo stesso; il codice ricevitore differisce leggermente. Io uso questo in un servizio che aggiorna una bandiera Bluetooth connesso che in altre parti del riferimento app.

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

Questo codice è per i profili auricolare, probabilmente funzionerà per altri profili anche. In primo luogo è necessario fornire il profilo ascoltatore (codice 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
        }
    }
}

Poi durante il controllo del bluetooth:

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

Ci vuole un po 'di tempo fino a quando onSeviceConnected viene chiamato. Dopo di che si può ottenere l'elenco dei dispositivi cuffia collegata da:

mBluetoothHeadset!!.connectedDevices

BluetoothAdapter.getDefaultAdapter().isEnabled -> restituisce vero quando Bluetooth è aperto

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

audioManager.isBluetoothScoOn -> restituisce vero quando dispositivo collegato

So che questa discussione è una specie di vecchio, ma ho davvero bisogno di sapere se un dispositivo è stato collegato a destra all'avvio del mio app, e ho trovato la soluzione!

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

E 'disponibile proprio qui, in Kotlin così: https: // developer.android.com/guide/topics/connectivity/bluetooth#QueryPairedDevices

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top