6

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

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

但是方法中的,ACTION_ACL_FOUNDACTION_ACL_DISCONNECT_REQUESTED无法解析或者不是字段。ACTION_ACL_DISCONNECTEDonReceive

那么为什么它们不能解决呢?

还是有另一种新的解决方案?

4

1 回答 1

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

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

它们在 BluetoothDevice 中:(http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#ACTION_ACL_CONNECTED

您也只注册以监听 3 个动作,因此除非您在其他地方为它们注册,否则您实际上并不需要其他动作。

于 2013-10-25T08:21:32.773 回答