Android Bluetooth Pairing without User Enter Pin and Confirmation Using Android API

前端 未结 3 650
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 05:24

I\'m a beginner in Android programming since I only started 3 months ago. I\'m doing a project which connects the android app to arduino using bluetooth. I already have a co

3条回答
  •  执笔经年
    2020-12-13 05:57

    I also faced the same problem and after all the research, I figured out the below solution.

    (Tested and working!!!)

    I am basically looking for a particular bluetooth device (I know MAC address) and pair with it once found. The first thing to do is to create pair request using boradcast receiver and handle the request as below.

    IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
                    intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
                    registerReceiver(broadCastReceiver,intentFilter);
    

    You need to write the broadcastReceiver and handle it as below.

    String BLE_PIN = "1234"
    private BroadcastReceiver broadCastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action))
            {
                BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                bluetoothDevice.setPin(BLE_PIN.getBytes());
                Log.e(TAG,"Auto-entering pin: " + BLE_PIN);
                bluetoothDevice.createBond();
                Log.e(TAG,"pin entered and request sent...");
            }
        }
    };
    

    Voila! You should be able to pair to bluetooth device without ANY MANUAL INTERVENTION.

    Hope this helps :-) Please make it right answer if it works for you.

提交回复
热议问题