TABLE OF CONTENTS (HIDE)

Android Programming

Networking with Bluetooth

Introduction

Android Bluetooth API supports:

  • Scanning for other Bluetooth devices
  • Querying the local Bluetooth adapter for paired Bluetooth devices
  • Establishing RFCOMM channels
  • Connecting to other devices through service discovery
  • Transferring data to and from other devices
  • Managing multiple connections

In order for Bluetooth devices to transfer data between each other:

  1. First, they must form a channel of communication using a pairing process. One device, a discoverable device, makes itself available for incoming connection requests. Another device finds the discoverable device using a service discovery process. After the discoverable device accepts the pairing request, the two devices complete a bonding process where they exchange security keys. The devices cache these keys for later use.
  2. After the pairing and bonding processes are complete, the two devices exchange information.
  3. When the session is complete, the device that initiated the pairing request releases the channel that had linked it to the discoverable device. The two devices remain bonded, however, so they can reconnect automatically during a future session as long as they're in range of each other and neither device has removed the bond.
Android Permissions

You need to declare these permissions in the "AndroidManifest.xml":

<manifest ... >
   <uses-permission android:name="android.permission.BLUETOOTH" />
   <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
   ......
</manifest>
  • android.permission.BLUETOOTH: for performing Bluetooth communication, such as requesting a connection, accepting a connection, and transferring data.
  • android.permission.BLUETOOTH_ADMIN: for discovering local Bluetooth devices.
  • android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION: for gathering information about the location of the user. This information may come from the user's own device, or Bluetooth beacons in use at locations such as shops.

Android Bluetooth By Examples

Example 1

Start "Android Studio" ⇒ Start a new Android Studio Project ⇒ In "Create Android Project" dialog, enter "Hello Bluetooth" in "Application Name" and "example.com" in "Company Domain". Set your "Project Location". Uncheck "Include C++ Support" ⇒ In "Select the form factors and minimum SDK", check "Phone and Tablet" and choose "API 15" ⇒ In "Add an Activity to Mobile", select "Empty Activity" ⇒ In "Creates a new empty activity", enter "MainActivity" to "Activity Name" and "activity_main" to "Layout name" ⇒ Finish.

Setting up Bluetooth

First, get a BluetoothAdapter via static method BluetoothAdapter.getDefaultAdapter(). It returns the device's Bluetooth adapter; or null if the device does not support Bluetooth.

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
   // Device doesn't support Bluetooth
   Toast.makeText(this, "error: bluetooth not supported", Toast.LENGTH_LONG).show();
}

Next, enable Bluetooth:

private static final int REQUEST_ENABLE_BT = 1;
......

if (!bluetoothAdapter.isEnabled()) {
    Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBluetoothIntent, REQUEST_ENABLE_BT);
}

// Called Back when the started activity returns a result
public void onActivityResult(int requestCode, int resultCode, Intent result) {
   if (requestCode == REQUEST_ENABLE_BT) {  // Match the request code
      if (resultCode == RESULT_OK) {
         Toast.makeText(this, "Bluetooth Turned on", Toast.LENGTH_LONG).show();
      } else {   // RESULT_CANCELED
         Toast.makeText(this, "error: turning on bluetooth", Toast.LENGTH_LONG).show();
      }
   }
}
  • The isEnabled() returns false if Bluetooth is disabled.
  • To enable Bluetooth, call startActivityForResult() with an intent BluetoothAdapter.ACTION_REQUEST_ENABLE. This call issues a request to enable Bluetooth through the system settings without stopping your application. A dialog appears to request user permission to enable Bluetooth.
  • The REQUEST_ENABLE_BT is a constant that must be greater than 0. The system passes this request code back to onActivityResult(); and result code of RESULT_OK or RESULT_CANCELLED.
  • You can invoke disable() to disable bluetooth.
Finding Devices

Using the BluetoothAdapter, you can find remote Bluetooth devices either through device discovery or by querying the list of paired devices.

Device discovery searches Bluetooth-enabled devices and requests some information. A Bluetooth device responds to a discovery request only if it is currently accepting information requests by being discoverable. It responds to the discovery request by sending back information such as device's name, its class and its MAC address. The discovering device can then choose to initiate a connection to the discovered device.

Once a connection is established, a pairing request is presented to the user. When a device is paired, the basic information about that device (such as device name, class and MAC address) is saved, and connection can be initiated later without performing discovery.

Before performing device discovery, we shall query the set of paired devices to see if the desired device is already known, via getBondedDevices(). For example,

Set pairedDevices = mBluetoothAdapter.getBondedDevices();

if (pairedDevices.size() > 0) {
    // There are paired devices. Get the name and address of each paired device.
    for (BluetoothDevice device : pairedDevices) {
        String deviceName = device.getName();   // device name
        String deviceHardwareAddress = device.getAddress(); // MAC address
    }
}
 
Link to Android's References and Resources