Android bluetooth example

I’m starting more detailed work on Bluetooth sharing.
I found this snippet of code on the dev guide that looked very similar to a TCP socket which I did a while ago.
The code below is taken from :
http://developer.android.com/guide/topics/wireless/bluetooth.html

private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer = new byte[1024];  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI Activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    /* Call this from the main Activity to send data to the remote device */
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }

    /* Call this from the main Activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

 

4 comments on “Android bluetooth example”

  1. uldara

    did you have full detail about Bluetooth Step by Step.
    Please help.
    Thanks

  2. noslen

    Hi uldara,
    What specifically did you need help with?

  3. PRANAY

    Can u send me tutorial for accepting text file from a paired Bluetooth device or how to track a Bluetooth received file

  4. Ginia

    Can u please send me the code of how to send and recieve an image through bluetooth socket.?

Leave a Reply

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