我如何进行蓝牙自动配对?

时间:2019-01-10 16:24:24

标签: java android

我正在使用Android Studio,正在做一个包含2个活动的应用程序。在第一个设备中,您可以扫描附近的设备,而当您触摸某个设备时,该应用程序将切换到下一个活动。如果之前未配对过设备,则连接失败或应用程序崩溃。我不确定Broadcast和createBond的顺序

我尝试将createBond()放在setPairingConfirmation()之后

 private BroadcastReceiver mReceiver5 = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (action.equals(BluetoothDevice.ACTION_PAIRING_REQUEST)) {
            try {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // int pin=intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY", 0);
                // the pin in case you need to accept for an specific pin
                int pin = intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY",CONTRASEÑA);
                Log.d(TAG, "Start Auto Pairing. PIN = " +intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY",CONTRASEÑA));
                byte[] pinBytes;
                // pinBytes = (""+pin).getBytes("UTF-8");
                pinBytes = ("" + pin).getBytes("UTF-8");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    device.setPin(pinBytes);
                    device.setPairingConfirmation(true);
                }

            } catch (Exception e) {
                Log.e(TAG, "Error occurs when trying to auto pair");
                e.printStackTrace();
            }
        }
    }
}

 private AdapterView.OnItemClickListener mDeviceClickListener =
        new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView av, View v, int arg2, long arg3) {
        // Se detiene discovery porque es muy intenso para la memoria
        mBTAdapter.cancelDiscovery();

        Log.d(TAG, "onItemClick: clickeaste sobre un dispositivo");
        String deviceName = mBTDevices.get(arg2).getName();
        String deviceAddress = mBTDevices.get(arg2).getAddress();

        Log.d(TAG, "onItemClick: deviceName = " + deviceName);
        Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);

        // Crea el enlace
        // NOTA: se requiere api 17 o más
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
            // Entra si la versión del SDK es mayor a versión Lollipop
            Log.d(TAG, "Tratando de emparejar con: " + deviceName);
            mBTDevices.get(arg2).createBond();
        }

        IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
        registerReceiver(mReceiver5,intentFilter);

        Intent i = new Intent(DispositivosBT.this, MainActivity.class); //
        i.putExtra(EXTRA_DEVICE_ADDRESS, deviceAddress);

        startActivity(i);
    }
};

现在,当我尝试连接至未配对的设备时,有时应用程序停止工作,并且使用其他计时器,则连接失败,但应用程序继续工作,如果我再次尝试连接,则连接成功。 我需要连接一个未配对的设备并更改为下一个活动

1 个答案:

答案 0 :(得分:0)

我找到的解决方案就是这个:

   private AdapterView.OnItemClickListener mDeviceClickListener =
                    new AdapterView.OnItemClickListener() {
                        public void onItemClick(AdapterView av, View v, int arg2, long arg3) {
                        cancelarDiscovery(mBTAdapter);

                        Log.d(TAG, "onItemClick: clickeaste sobre un dispositivo");
                        String deviceName = mBTDevices.get(arg2).getName();
                        deviceAddress = mBTDevices.get(arg2).getAddress();

                        Log.d(TAG, "onItemClick: deviceName = " + deviceName);
                        Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);

                        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
                            Log.d(TAG, "Trying to pair with: " + deviceName);
                            mBTDevices.get(arg2).createBond();
                        }

                        if(mBTDevices.get(arg2).getBondState() == BluetoothDevice.BOND_BONDED){
                            nextActivity();
                        }
                      }
                };