如何检查设备的蓝牙连接是否断开?

sil*_*aut 5 android android-bluetooth

我想知道我与设备的蓝牙连接何时断开连接.我发现这个要检查:

    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
   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 (BluetoothAdapter.ACTION_ACL_CONNECTED.equals(action)) {
               //Device is now connected
            }
            else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                //Done searching
            }
            else if (BluetoothAdapter.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
               //Device is about to disconnect
            }
            else if (BluetoothAdapter.ACTION_ACL_DISCONNECTED.equals(action)) {
               //Device has disconnected
            }           
        }
    };
Run Code Online (Sandbox Code Playgroud)

但是ACTION_ACL_FOUND,ACTION_ACL_DISCONNECT_REQUESTED并且ACTION_ACL_DISCONNECTEDonReceive方法中无法解决或者不是一个领域.

那为什么他们无法解决?

或者还有另一种新的解决方案吗?

Ken*_*olf 4

将您的更改onReceive为:

    @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
        }           
    }
Run Code Online (Sandbox Code Playgroud)

您提到的 3 个字段在 BluetoothAdapter 中不存在:( http://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html )

它们位于蓝牙设备中:(http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#ACTION_ACL_CONNECTED

您也只注册监听 3 个操作,因此您并不真正需要其他操作,除非您在其他地方注册它们。