Android Bluetooth file sending-ThrowExceptions

Exception or error:

I am trying to send a file over bluetooth in an android device. I have done discovery, connection and have made a bluetooth socket. Problem is when i am writing the byte array in the output stream of the bluetooth socket, the recieving side does not receive anything although it accept that something is being sent.

Here’s what Iam doing (bad is the bluetooth adaptor)

Please advise.

        BluetoothDevice dev = bad.getRemoteDevice(a);

        dev.createRfcommSocketToServiceRecord(new UUID(1111, 2222));
        Method m = dev.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
        bs = (BluetoothSocket) m.invoke(dev, Integer.valueOf(1));
        tmpOut = bs.getOutputStream();
    }catch(Exception e)


    File f = new File(filename);

    byte b[] = new byte[(int) f.length()];
        FileInputStream fileInputStream = new FileInputStream(f);;
    }catch(IOException e)
        Log.d(TAG, "Error converting file");
        Log.d(TAG, e.getMessage());

    try {
    } catch (IOException e) {
        // TODO Auto-generated catch block
How to solve:

I am using the below code snipped to connect to the serial service in a remote Bluetooth device and it is working fine for me. Just make sure that the other device (can be mobile or PC) has a server socket for serial communication over Bluetooth (see the server side code below)

Client Side:

UUID serialUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothDevice btDevice = btAdapter.getRemoteDevice(BTAddress); // Get the BTAddress after scan
BluetoothSocket btSocket = btDevice.createRfcommSocketToServiceRecord(SERIAL_UUID);
InputStream iStream = btSocket.getInputStream();
OutputStream oStream = btSocket.getOutputStream();

Server Side:

UUID serialUUID = new UUID("1101", true);
String serviceURL = "btspp://localhost:" + serialUUID
        + ";name=Android BT Server;authorize=false;authenticate=false";
StreamConnectionNotifier connectionNotifier = (StreamConnectionNotifier) Connector
// Blocking method will wait for client to connect
StreamConnection connection = connectionNotifier.acceptAndOpen();

RemoteDevice remoteDevice = RemoteDevice.getRemoteDevice(connection);
InputStream btInput = connection.openInputStream();
OutputStream btOutput = connection.openOutputStream();


Why not use the standard api call instead of calling through reflection, eg:

BluetoothSocket socket =  destination
                              .createRfcommSocketToServiceRecord(new UUID(...)) ;

Also your catch block is empty. Are you sure the socket was connected without any exception? Connect will throw IOException if the connection failed for some reason. See this link


It might be because dev and bs go out of scope before tmpout is used because they are declared within your try/catch block.

Leave a Reply

Your email address will not be published. Required fields are marked *