How to pair Bluetooth device programmatically Android

前端 未结 8 1985
不知归路
不知归路 2020-11-27 12:35

I am developing an application where I want to connect a Bluetooth device main issue is I don\'t want user to enter required pin instead application should do that by himsel

8条回答
  •  庸人自扰
    2020-11-27 13:25

        BluetoothSocket bluetoothSocket = null;
        try {
            bluetoothSocket = device.createRfcommSocketToServiceRecord(UUID.fromString(UUID_DIVING));
        } catch (IOException e) {
            Log.i("Bluetooth", "IOException = " + e.getMessage());
            e.printStackTrace();
        }
    
        try {
            byte[] pin = (byte[]) BluetoothDevice.class.getMethod("convertPinToBytes", String.class).invoke(BluetoothDevice.class, "0000");
            Method m = device.getClass().getMethod("setPin", byte[].class);
            m.invoke(device, (Object) pin);
            device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            Log.i("Bluetooth", "IOException = " + e.getMessage());
            e.printStackTrace();
        }
    
        try {
            if (bluetoothSocket != null) {
                bluetoothSocket.connect();
                Log.i("Bluetooth", "bluetoothSocket.connect() ");
                InputStream inputStream = bluetoothSocket.getInputStream();
                OutputStream outputStream = bluetoothSocket.getOutputStream();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    

提交回复
热议问题