Android Bluetooth Example: GitHub Repository

Bluetooth is an essential feature for many Android apps, enabling communication between Android devices and external hardware like headphones, speakers, fitness trackers, or smart home devices. To help developers learn how to integrate Bluetooth functionality into their Android apps, many examples are available on GitHub. Below, I'll guide you through a simple example of how you can use Bluetooth in your Android app, along with a link to a helpful GitHub repository.

Example: Simple Bluetooth Application

This example demonstrates how to scan for nearby Bluetooth devices, connect to one, and then send/receive data using Bluetooth. We will focus on Bluetooth Low Energy (BLE) devices, which are commonly used for IoT devices, fitness trackers, and other wireless peripherals.

Prerequisites

  1. Android Studio installed on your computer.
  2. A device running Android 6.0 (API level 23) or higher.
  3. A Bluetooth-enabled Android device or emulator with Bluetooth support.

Steps to Implement Bluetooth in Android App

Step 1: Add Permissions to AndroidManifest.xml

First, add the required Bluetooth permissions to the AndroidManifest.xml file. The following permissions are necessary to enable Bluetooth scanning and communication:

xml
<uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> <uses-permission android:name="android.permission.BLUETOOTH_SCAN"/> <uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  • BLUETOOTH and BLUETOOTH_ADMIN allow basic Bluetooth functionality.
  • BLUETOOTH_SCAN and BLUETOOTH_CONNECT are used for Bluetooth scanning and communication in Android 12 and later.
  • ACCESS_FINE_LOCATION is required to scan for nearby Bluetooth devices.

Step 2: Check Bluetooth Availability

In your MainActivity.java or the activity class, check if Bluetooth is available on the device and if it's enabled:

java
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { // Device doesn't support Bluetooth Toast.makeText(this, "Bluetooth is not supported on this device.", Toast.LENGTH_SHORT).show(); finish(); } else if (!bluetoothAdapter.isEnabled()) { // Request Bluetooth to be enabled Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, 1); }

Step 3: Scan for Bluetooth Devices

Next, you can scan for Bluetooth devices. If you are using Bluetooth Low Energy (BLE), you'll need to create a BluetoothLeScanner and start scanning.

java
BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner(); ScanSettings settings = new ScanSettings.Builder().build(); List<ScanFilter> filters = new ArrayList<>(); bluetoothLeScanner.startScan(filters, settings, scanCallback);

The scanCallback handles the scanning results:

java
private ScanCallback scanCallback = new ScanCallback() { @Override public void onScanResult(int callbackType, ScanResult result) { super.onScanResult(callbackType, result); BluetoothDevice device = result.getDevice(); String deviceName = device.getName(); String deviceAddress = device.getAddress(); Log.d("Bluetooth", "Found device: " + deviceName + " (" + deviceAddress + ")"); } @Override public void onBatchScanResults(List<ScanResult> results) { super.onBatchScanResults(results); } @Override public void onScanFailed(int errorCode) { super.onScanFailed(errorCode); } };

Step 4: Pair and Connect to a Bluetooth Device

After detecting a Bluetooth device, you can attempt to connect to it. Use the BluetoothDevice object to establish a connection:

java
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress); BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID); socket.connect();

MY_UUID is a unique identifier for the Bluetooth service.

Step 5: Send/Receive Data

Once connected to a Bluetooth device, you can send or receive data over the Bluetooth socket. Use an InputStream and OutputStream to handle data transfer:

java
OutputStream outputStream = socket.getOutputStream(); InputStream inputStream = socket.getInputStream(); // Sending data to Bluetooth device String message = "Hello Bluetooth!"; outputStream.write(message.getBytes()); // Receiving data from Bluetooth device byte[] buffer = new byte[1024]; int bytes; while ((bytes = inputStream.read(buffer)) != -1) { String receivedData = new String(buffer, 0, bytes); Log.d("Bluetooth", "Received: " + receivedData); }

Step 6: Close Connection

Don’t forget to close the Bluetooth socket when you're done with the communication:

java
socket.close();

GitHub Example: Bluetooth Android Application

To help you better understand and get started with Bluetooth integration on Android, there are several GitHub repositories that provide complete examples.

One such example is the BluetoothLEExample repository by Google. This repository contains an implementation of Bluetooth Low Energy (BLE) scanning, connecting, and communication with Bluetooth peripherals.

You can clone or download the repository using GitHub:

bash
git clone https://github.com/googlesamples/android-BluetoothLeGatt.git

The BluetoothLeGatt sample app demonstrates how to:

  • Scan for nearby Bluetooth Low Energy (BLE) devices.
  • Connect to a BLE device.
  • Communicate with the device using GATT (Generic Attributes) profiles.
  • Read and write data to the device.

Conclusion

Integrating Bluetooth functionality into an Android app requires handling permissions, scanning for devices, establishing connections, and sending/receiving data. Using Bluetooth, especially Bluetooth Low Energy (BLE), can enable your app to interact with a wide range of devices, from fitness trackers to smart home appliances.

If you're new to Bluetooth on Android, using example repositories from GitHub like the BluetoothLeGatt repository is a great way to learn. By leveraging sample code and building upon it, you can add Bluetooth features to your own Android apps quickly and effectively.

For further customization or advanced features, you can explore more on the official Android Bluetooth API documentation.