Send request for pairing

Asked

Viewed 838 times

0

I am developing an android app for bluetooth connection, currently my application is listing the paired devices and search new devices.

I need at this point an example code that picks up the address 1b:2f:5d:6a:7a and submit 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) { }
    }
}
  • 1

    Hello @Gilliard-saints have you tried anything? if yes it would be interesting to put your attempt so that we can analyze and correct/improve your code.

  • 1

    I added my question the code I have, but I do not know if it is to request pairing and do not know where I enter the address of the device I want to connect.

1 answer

2

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

This code uses a treatment try-catch, that some may not like, but it is to be able to treat 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;
    }
}
  • I like the code, but this code requires pairing ?

  • It serves to specify which service you want to access from the other device, for example, in the case of the example is to connect using the Bluetooth serial port protocol. But it could be another service, like headset, keyboard, etc...

  • I get it, but this code calls for pairing with the other device ?

  • On the devices I tested, whenever a connection with an unpaired device starts, Android automatically started the pairing process. Hence the special treatment in the code to see if the device was still pairing, and in such case, show an error message, but something like "Device still pairing, try again later..."

  • Cool, I have just one more question, I would like after searching for new unmatched devices, only be displayed in the list the devices of the Samsung brand, how can I do ?

  • This can be done by comparing the first three bytes of the device’s MAC, which corresponds to the company (vendor). I found this site here, which can help you: http://www.coffer.com/mac_find/? string=Samsung

  • Would you have an example that compares the MAC code ?

  • Since you have a string with the MAC, in the form "XX:XX:XX:XX:XX:XX", you can do MAC.toLowerCase(Locale.US).startsWith("0a:00:12"), Suppose you want to know if the MAC starts by "0a:00:12" (Remember to write in lowercase letters, because of the toLowerCase())

  • Thanks for the help.

  • No problem! If everything works out, just be sure to mark the question as answered :)

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.