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

前端 未结 3 652
被撕碎了的回忆
被撕碎了的回忆 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:37

    Yes this possible to do by code

    In you main activity add the following code

    BluetoothReceiver myreceiver = new BluetoothReceiver();
    var intentfilterparingrequest = new IntentFilter(BluetoothDevice.ActionPairingRequest);
    RegisterReceiver(myreceiver, intentfilterparingrequest);
    

    In your broadcast receiver write following code, if not create a new broadcast receiver

    public class BluetoothReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            string BLE_PIN = "0000";
            var action = intent.Action;
            switch (action)
            {
                case BluetoothDevice.ActionPairingRequest:
                    BluetoothDevice bluetoothDevice = 
                  (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
                    bluetoothDevice.SetPin(Encoding.ASCII.GetBytes(BLE_PIN));
                    bluetoothDevice.CreateBond();
                    break;
            }
        } 
    }
    

提交回复
热议问题