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

时间:2013-10-25 08:07:02

标签: 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
            }           
        }
    };

ACTION_ACL_FOUND方法中的ACTION_ACL_DISCONNECT_REQUESTEDACTION_ACL_DISCONNECTEDonReceive无法解析或不是字段。

那为什么他们无法解决?

还是有其他新解决方案吗?

1 个答案:

答案 0 :(得分:2)

将您的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个动作,所以除非您在其他地方注册,否则您不需要其他动作。