Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Send and Receive Data Using Sockets Via Bluetooth in Android Device - 5 Steps

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 7.68k
    Comment on it

    Bluetooth communication channel is the easier way to transfer data. If you need to send data between two devices and your device did not support WIFI or any other communication channel except Bluetooth, then these few steps will help you for easy data transfer. A Bluetooth communication is slower in comparison to the WIFI(hotspot) but for small files or text in a specified range, this option is suited mostly.

     

     

    So, In this tutorial, I am providing the "5 Steps Guide to Send and Receive Data Using Sockets Via Bluetooth in Android Device".

     

    Let's get started with the steps for creating a demo on Bluetooth device communication using sockets.

     

    Step 1: Connect remote Bluetooth device with MAC address

    // Try to get the remote device MAC address and establish the connection with the device 
    private void connectDevice() {
    	String address;  // Get the device MAC address
    	// Create BluetoothDevice object with remote device address
    	BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    	// Call connect method with device(BluetoothDevice) param
    	connect(device);
    }

     

    Step 2: Create seperate thread for socket connection

    // Initially, on Bluetooth class we need to start the ConnectThread to initiate a connection on a separate thread.
        public synchronized void connect(BluetoothDevice device) {
            Log.d(TAG, "bluetooth device: " + device);
    
            // If mConnected thread is already connected cancel it and start the thread to the device
            mConnectThread = new ConnectThread(device);
            mConnectThread.start();	// thread start
        }

     

    Step 3: Connect devices using socket for safe communication

    // This thread will first create a socket with the device and after a successful connection, it will try to connect with the device. 
        private class ConnectThread extends Thread {
            private final BluetoothSocket mmSocket;
            private final BluetoothDevice mmDevice;
    
            public ConnectThread(BluetoothDevice device) {
                mmDevice = device;
                BluetoothSocket tmpSocket = null;
    
                // Creating socket connection with other device
                try {
                       tmpSocket = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
                    	
    		   // connection insecure case
                       //tmpSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
                    
                } catch (IOException e) {
                    e.printStackTrace();
                }
    	    mmSocket = tmpSocket;
            }
    
            public void run() {
                // cancelDiscovery will stop any device findings and boost your socket connection
                mAdapter.cancelDiscovery();
    
                try {
                    // Got successfull connection otherwise exception
                    mmSocket.connect();
                } catch (IOException e) {
                    // If exception is caught try to close the socket
                    try {
                        mmSocket.close();
                    } catch (IOException e2) {
                        e2.printStackTrace();
                    }
                    connectionFailed();
                    return;
                }
    
                // Now time to start the connected thread
                connected(mmSocket, mmDevice);
            }
        }
    

     

    Step 4: New thread for file transfer after connection

    // If one succeeds with the socket connection, now time to manage connection for sending and receiving files in a separate thread.
        public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
    
            // Start the thread to manage the connection and perform transmissions
            mConnectedThread = new ConnectedThread(socket);
            mConnectedThread.start();
        }
    

     

    Step 5: Read and Write bytes

    // Incoming and the outgoing strings are carried out inside this thread read is for reading incoming messages through a socket and write is for sending messages to the remote device
        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 BluetoothSocket input and output streams
                try {
                    tmpIn = socket.getInputStream();
                    tmpOut = socket.getOutputStream();
                } catch (IOException e) {
                    // socket not created
    		e.printStackTrace();
                }
    
                mmInStream = tmpIn;
                mmOutStream = tmpOut;
            }
    
            public void run() {
                byte[] buffer = new byte[1024];
                int bytes;
    		// receiving message
                    try {
                        // Read from the InputStream
                        bytes = mmInStream.read(buffer);
    
                        // message is in bytes form so reading them to obtain message
                        mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer)
                                .sendToTarget();
                    } catch (IOException e) {
    		    // connection was lost and start your connection again
                        Log.e(TAG, "disconnected", e);
                        break;
                    }
            }
    	
            public void write(byte[] buffer) {
                try {
                    mmOutStream.write(buffer);
    
                    // mHandler is to show send message from device
                    mHandler.obtainMessage(Constants.MESSAGE_WRITE, -1, -1, buffer);
                    mHandler.sendToTarget();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

     

    That's all, Now your device is ready to share data with another device. If you have any questions or inputs please feel free to write in comment section below.

    Send and Receive Data Using Sockets Via Bluetooth in Android Device - 5 Steps

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: