Android Connect Bluetooth device automatically after pairing programmatically

前端 未结 1 1037
遇见更好的自我
遇见更好的自我 2021-01-12 16:03

In my app I need pairing bluetooth device and immediately connect with it.

I have the following function in order to pairing devices:

public boolean          


        
相关标签:
1条回答
  • 2021-01-12 16:48

    I found the solution.

    First I need a BroadcastReceiver like:

    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                    // CONNECT
                }
            } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // Discover new device
            }
        }
    };
    

    And then I need register the receiver as follow:

    IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    context.registerReceiver(myReceiver, intentFilter);
    

    In this way the receiver is listening for ACTION_FOUND (Discover new device) and ACTION_BOND_STATE_CHANGED (Device change its bond state), then I check if the new state is BOND_BOUNDED and if it is I connect with device.

    Now when I call createBond Method (described in the question) and enter the pin, ACTION_BOND_STATE_CHANGED will fire and device.getBondState() == BluetoothDevice.BOND_BONDED will be True and it will connect.

    0 讨论(0)
提交回复
热议问题