Android Bluetooth accept() / connect() with already paired devices

后端 未结 3 1146
执笔经年
执笔经年 2021-02-04 18:56

I am having trouble connecting two Android devices via Bluetooth, which happens only when they have been paired before. I am running one as the server and the other as the clien

3条回答
  •  梦如初夏
    2021-02-04 19:41

    private static BluetoothSocket mSocket;
    BluetoothDevice selectDevice = null;
    

    void connectDevice(){
        if(mSocket == null) {
            //Log.d(TAG, "Socket is null");
            UUID SPP_UUID = UUID
                    .fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
            Set bondedDevices = BluetoothAdapter
                    .getDefaultAdapter().getBondedDevices();
            //Log.d(TAG, "Size: " + bondedDevices.size());
            /**
             * Select your divice form paired devices
             */
            for (BluetoothDevice bluetoothDevice : bondedDevices) {
                selectDevice = bluetoothDevice;
                //Log.d(TAG, bluetoothDevice.getName()+" "+bluetoothDevice.getAddress());
            }
    
            if(selectDevice.getBondState() == selectDevice.BOND_BONDED) {
                //Log.d(TAG, selectDevice.getName());
                try {
                    mSocket = selectDevice.createInsecureRfcommSocketToServiceRecord(SPP_UUID);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    //Log.d(TAG, "socket not created");
                    e1.printStackTrace();
                }
                try {
                    mSocket.connect();
                } catch (IOException e) {
                    try {
                        mSocket.close();
                        //Log.d(TAG, "Cannot connect");
                    } catch (IOException e1) {
                        //Log.d(TAG, "Socket not closed");
                        e1.printStackTrace();
                    }
                }
       }
    

提交回复
热议问题