Blog | G5 Cyber Security

Android Bluetooth App Connection Guide

TL;DR

This guide shows you how to connect an Android app to a Bluetooth module (like HC-05 or similar). It covers checking permissions, scanning for devices, pairing, and establishing a connection. We’ll also look at basic data transfer.

Connecting Your Android App to a Bluetooth Module

  1. Check Bluetooth Permissions:
    • In your app’s AndroidManifest.xml file, make sure you have the necessary permissions:
      <uses-permission android_name="android.permission.BLUETOOTH"/
      <uses-permission android_name="android.permission.BLUETOOTH_ADMIN"/
      <uses-permission android_name="android.permission.ACCESS_FINE_LOCATION"/
      
    • Important: ACCESS_FINE_LOCATION is required for Bluetooth scanning on newer Android versions, even if you don’t need location data. Explain this to your users in the app description.
  2. Enable Bluetooth:
    • Use the BluetoothAdapter class to check if Bluetooth is enabled:
      BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
      if (bluetoothAdapter == null) {
          // Device does not support Bluetooth
      }
      
      if (!bluetoothAdapter.isEnabled()) {
          Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
          startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
      }
    • REQUEST_ENABLE_BT is an integer you define (e.g., 1) to identify the result of this request.
  3. Scan for Bluetooth Devices:
    • Start a scan using BluetoothAdapter.startDiscovery():
      bluetoothAdapter.startDiscovery();
    • Register a BroadcastReceiver to listen for discovered devices:
      IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
      registerReceiver(mBroadcastReceiver, filter);
    • In your BroadcastReceiver’s onReceive() method, handle the found device:
      private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
              String action = intent.getAction();
              if (BluetoothDevice.ACTION_FOUND == action) {
                  BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                  // Add the device to your list
              }
          }
      };
    • Stop scanning after a reasonable time using bluetoothAdapter.cancelDiscovery().
  4. Pair with the Device:
    • Create a BluetoothDevice object from the discovered device’s address and MAC address.
    • Attempt to pair using device.createBond():
      if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
          // Request permission
      }
      
       device.createBond();
    • Pairing may require user confirmation on both the Android device and the Bluetooth module (e.g., entering a PIN).
  5. Connect to the Paired Device:
    • Get a BluetoothSocket from the paired device using UUID:
      UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); // Standard Serial Port Profile
      try {
          socket = device.createRfcommSocketToServiceRecord(MY_UUID);
      } catch (IOException e) {
          // Handle exception
      }
    • Connect to the socket:
      socket.connect();
    • Handle connection errors.
  6. Data Transfer:
    • Use an InputStream and OutputStream attached to the BluetoothSocket for sending and receiving data:
      InputStream inputStream = socket.getInputStream();
      OutputStream outputStream = socket.getOutputStream();
    • Write data to the outputStream (e.g., using outputStream.write(data)).
    • Read data from the inputStream (e.g., using inputStream.read(buffer)).
  7. Clean Up:
    • Close the socket and unregister the receiver when your activity is destroyed to prevent memory leaks:
      socket.close();
      unregisterReceiver(mBroadcastReceiver);
Exit mobile version