Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Connecting to a Bluetooth-Enabled Device

Author: Ashwini Shahapurkar -- Published? true -- FormatLanguage: W

Problem:

You need to connect to other bluetooth enabled device and want to communicate with it.

Solution:

You will use the android bluetooth api to connect to device using sockets. The communication will be over the socket streams.

Discussion:

For any bluetooth application you need to add these two permissions to AndroidManifest.xml

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />

You will create the socket connection to the other bluetooth device. Then you shall continuously listen for the data from the socket stream in a thread. You can write to connected stream outside the thread. The connection is a blocking call and bluetooth device discovery being a heavy process, may slow down the connection. So it is a good practice to cancel the device discovery before trying to connect to other device.

Note:The bluetooth socket connection is a blocking call and returns only if a connection is successful or if an exception occurs while connecting to device.

The BluetoothConnection shall create the socket connection to other device, once instantiated and start listening to the data from connected device.

private class BluetoothConnection extends Thread {
	private final BluetoothSocket mmSocket;
	private final InputStream mmInStream;
	private final OutputStream mmOutStream;
	byte[] buffer;

	// Unique UUID for this application, you may use different
	private static final UUID MY_UUID = UUID
			.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
			
	public BluetoothConnection(BluetoothDevice device) {
		
		BluetoothSocket tmp = null;

		// Get a BluetoothSocket for a connection with the given BluetoothDevice
		try {
			tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
		} catch (IOException e) {
			e.printStackTrace();
		}
		mmSocket = tmp;
		
		//now make the socket connection in separate thread to avoid FC
		Thread connectionThread  = new Thread(new Runnable() {
				
				@Override
				public void run() {
					// Always cancel discovery because it will slow down a connection
					mAdapter.cancelDiscovery();

					// Make a connection to the BluetoothSocket
					try {
						// This is a blocking call and will only return on a
						// successful connection or an exception
						mmSocket.connect();
					} catch (IOException e) {
						//connection to device failed so close the socket
						try {
							mmSocket.close();
						} catch (IOException e2) {
							e2.printStackTrace();
						}
					}
				}
			});
		
		connectionThread.start();
		
		InputStream tmpIn = null;
		OutputStream tmpOut = null;

		// Get the BluetoothSocket input and output streams
		try {
			tmpIn = socket.getInputStream();
			tmpOut = socket.getOutputStream();
			buffer = new byte[1024];
		} catch (IOException e) {
			e.printStackTrace();
		}

		mmInStream = tmpIn;
		mmOutStream = tmpOut;
	}

	public void run() {
		
		// Keep listening to the InputStream while connected
		while (true) {
			try {
				//read the data from socket stream
				mmInStream.read(buffer);
				// Send the obtained bytes to the UI Activity
			} catch (IOException e) {
				//an exception here marks connection loss
				//send message to UI Activity
				break;
			}
		}
	}

	public void write(byte[] buffer) {
		try {
			//write the data to socket stream
			mmOutStream.write(buffer);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void cancel() {
		try {
			mmSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

See Also:

Bluetooth Device discovery

No records found.