Send matching request

0

I'm developing an android application for bluetooth connection, currently my application is listing paired devices and searching for new devices.

I need at this point a code sample that takes the address 1b:2f:5d:6a:7a and sends a matching request.

private class AcceptThread extends Thread {
    private final BluetoothServerSocket mmServerSocket;

    public AcceptThread() {
        // Use a temporary object that is later assigned to mmServerSocket,
        // because mmServerSocket is final
        BluetoothServerSocket tmp = null;
        try {
            // MY_UUID is the app's UUID string, also used by the client code
            tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
        } catch (IOException e) { }
        mmServerSocket = tmp;
    }

    public void run() {
        BluetoothSocket socket = null;
        // Keep listening until exception occurs or a socket is returned
        while (true) {
            try {
                socket = mmServerSocket.accept();
            } catch (IOException e) {
                break;
            }
            // If a connection was accepted
            if (socket != null) {
                // Do work to manage the connection (in a separate thread)
                manageConnectedSocket(socket);
                mmServerSocket.close();
                break;
            }
        }
    }

    /** Will cancel the listening socket, and cause the thread to finish */
    public void cancel() {
        try {
            mmServerSocket.close();
        } catch (IOException e) { }
    }
}
    
asked by anonymous 09.05.2014 / 13:46

1 answer

2

I have this code here, which I use in my applications. It should give you a light on how to connect.

This code uses a try-catch treatment, which some may not like, but it is to be able to handle the case of the device still being paired.

private static final UUID SERIAL_PORT_SERVICE_CLASS_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothDevice mDevice;
private BluetoothSocket mSocket;
private BluetoothAdapter mAdapter;

private void createConnection() throws IOException {
    try {
        if (mAdapter == null)
            mAdapter = BluetoothAdapter.getDefaultAdapter();

        mDevice = mAdapter.getRemoteDevice("MAC ADDRESS DESEJADO");
        if (mDevice == null)
            throw new IOException();

        //Ou pode utilizar outro UUID, dependendo da necessidade
        mSocket = mDevice.createRfcommSocketToServiceRecord(SERIAL_PORT_SERVICE_CLASS_UUID);
        try {
            mSocket.connect();
        } catch (IOException e) {
            if ( < AINDA ESTAVA PAREANDO > ) {
                //É possível descobrir se o dispositivo já estava
                //pareado antes da chamada createRfcommSocketToServiceRecord(),
                //e tratar de uma forma diferente aqui, pedindo para o usuário
                //aguardar, ou outra mensagem que não seja de erro fatal

                //Para isso, basta verificar se o dispositivo estava ou não no Set
                //retornado por mAdapter.getBondedDevices()
                return;
            }

            try {
                //Caso contrário, tenta outro método para criar o socket
                //(para funcionar no HTC desire) - crédito de Michael Biermann
                Method method = mDevice.getClass().getMethod("createRfcommSocket",
                                                             new Class[] { int.class});
                mSocket = (BluetoothSocket)method.invoke(mDevice, Integer.valueOf(1));
                mSocket.connect();
            } catch (Exception ex) {
                //O reflection falhou, aborta por aqui
                throw new IOException(e);
            }
        }

        //A partir daqui é OK chamar mSocket.getIntputStream() e
        //mSocket.getOutputStream()

    } catch (IOException e) {
        //Ver comentários sobre pareamento acima (o tratamento deve ser repetido aqui)
        throw e;
    }
}
    
09.05.2014 / 14:36