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

Accepting Connections from a Bluetooth Device

Author: Rachee Singh -- Published? true -- FormatLanguage: W

Problem:

Creating a listening server for Bluetooth Connections.

Solution:

For Bluetooth devices to interact, prior to the establishment of a connection, one of the communicating devices acts like a server. It obtains an instance BluetoothServerSocket and listens for incoming requests. This instance is obtained by calling the listenUsingRfcommWithServiceRecord method on the Bluetooth adapter

Discussion:

With the instance of BluetoothServerSocket, we can start listening for incoming requests from remote devices through the start() method. Listening is a blocking process so we have make a new thread and call it within the thread otherwise the UI of the application becomes unresponsive.


//Making the host device discoverable
startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE),DISCOVERY_REQUEST_BLUETOOTH);
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == DISCOVERY_REQUEST_BLUETOOTH) {
			boolean isDiscoverable = resultCode > 0;
			if (isDiscoverable) {
				UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666");
				String serverName = "BTserver";
				final BluetoothServerSocket bluetoothServer = bluetoothAdapter.listenUsingRfcommWithServiceRecord(serverName, uuid);
				
				Thread listenThread = new Thread(new Runnable() {
				
					public void run() {
						try {
							
							BluetoothSocket serverSocket = bluetoothServer.accept();

						} catch (IOException e) {
						
							Log.d("BLUETOOTH", e.getMessage());
						}
					}
				});
				listenThread.start();
			}
		}
	}
No records found.