Transmitting Data Using Bluetooth Sockets

Once a connection has been established, you will have a Bluetooth Socket on both the client and the server devices. From this point onward there is no significant distinction between them: you can send and receive data using the Bluetooth Socket on both devices.

Data transfer across Bluetooth Sockets is handled via standard Java InputStream and OutputStream objects, which you can obtain from a Bluetooth Socket using the appropriately named getInputStream and getOutputStream methods, respectively.

Listing 13-11 shows two simple skeleton methods, the first used to send a string to a remote device using an Output Stream, and the second to listen for incoming strings using an Input Stream. The same technique can be used to transfer any streamable data.

LISTING 13-11: Sending and receiving strings using Bluetooth Sockets download on private void sendMessage(String message){ OutputStream outStream;

outStream = socket.getOutputStream();

// Add a stop character.

byte[] byteArray = (message + " ").getBytes(); byteArray[byteArray.length — 1] = 0;


private String listenForMessage() String result = ""; int bufferSize = 1024; byte[] buffer = new byte[bufferSize];

InputStream instream = socket.getInputStream();

bytesRead =; if (bytesRead != -1) {

while ((bytesRead == bufferSize) && (buffer[bufferSize-1] != 0)){ message = message + new String(buffer, 0, bytesRead); bytesRead =;

message = message + new String(buffer, 0, bytesRead — 1); return result;

} catch (IOException e) {} return result;

Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide

Post a comment