Back to Projects

Bluetooth Serial

Android Java

A streamlined Android wrapper for Bluetooth RFCOMM (SPP) communication. It simplifies connecting to microcontrollers like Arduino or ESP32 by handling device discovery, pairing dialogs, and background thread management for serial data streams.

Integration

Add the two core classes to your project package.

  • BluetoothSerial.java: Handles sockets & I/O.
  • BluetoothHelper.java: Handles discovery & UI.

Permissions

Add standard Bluetooth permissions to your AndroidManifest.xml.

<uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <!-- For Android 12+ --> <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />

1. Select Device

Use BluetoothHelper to show a dialog of paired devices. When the user selects one, it launches the target Intent with the MAC address.

// On button click in your Launch Activity BluetoothHelper btHelper = new BluetoothHelper(); if (btHelper.is_supported()) { // Prepare intent to launch your Control Activity Intent intent = new Intent(this, ControlActivity.class); // Show dialog. Selected MAC will be put into intent extra "MAC" btHelper.Default(this, intent); }

2. Connect

In your target activity, retrieve the MAC address and initialize BluetoothSerial to start the connection thread.

public class ControlActivity extends Activity { BluetoothSerial btSerial; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String macAddress = getIntent().getStringExtra("MAC"); btSerial = new BluetoothSerial(); // Starts async connection (Shows "Connecting..." dialog) btSerial.Begin(macAddress, this); } @Override protected void onDestroy() { super.onDestroy(); btSerial.Close(); // Clean up socket } }

3. Send Data

Once connected, use the write methods to send commands to the serial device.

// Send a string with newline (e.g. for Arduino Serial.readStringUntil) btSerial.PrintLine("LED_ON"); // Send raw string bytes btSerial.WriteAllText("Hello World"); // Send single character btSerial.Write('A');

API: BluetoothSerial

Method Description
Begin(mac, context) Connects to the device MAC. Shows a progress dialog.
Close() Closes the active socket and stops the thread.
PrintLine(str) Sends string appended with \n.
WriteAllText(str) Sends string bytes without modification.
Write(char) Sends a single character byte.

API: BluetoothHelper

Method Description
is_supported() Returns true if the device has Bluetooth hardware.
enable() Triggers the system intent to enable Bluetooth if disabled.
Default(ctx, intent) Shows a dialog of paired devices. On selection, adds the MAC to the intent and starts the activity.