With the BroadcastReceiver plugin, it is easy to write a Bluetooth discovery application with Delphi.

Drop the BroadcastReceiver component onto the form, double click on the BroadcastReceiver, and put in the code to recognize the Bluetooth device.

Here's what the code looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
procedure TForm6.BroadcastReceiver1Receive(AContext: JContext;
  AIntent: JIntent);
var
  LJAction: JString;
  LDeviceName, LAddress: string;
  LParcel: JParcelable;
  LDevice: JBluetoothDevice;
begin
  LJAction := AIntent.getAction;
 
  if LJAction.compareTo(TJBluetoothDevice.JavaClass.ACTION_FOUND)=0 then
    begin
      LParcel := AIntent.getParcelableExtra(TJBluetoothDevice.JavaClass.EXTRA_DEVICE);
      LDevice := TJBluetoothDevice.Wrap((LParcel as ILocalObject).GetObjectID);
      if LDevice.getBondState <> TJBluetoothDevice.JavaClass.BOND_BONDED then
        begin
          LDeviceName := JStringToString(LDevice.getName);
          LAddress    := JStringToString(LDevice.getAddress);
          Log.d(Format('Bluetooth device name: %s', [LDeviceName]));
          Log.d(Format('Bluetooth device addr: %s', [LAddress]));
        end;
    end else
  if LJAction.compareTo(TJBluetoothAdapter.JavaClass.ACTION_DISCOVERY_FINISHED) = 0 then
    begin
      Log.d('Bluetooth discovery finished');
    end;
 
end;
 
procedure TForm6.btnEnableDiscoveryClick(Sender: TObject);
begin
  EnsureBroadcastReceiverSet;
  CallInUIThread(procedure
  var
    BluetoothAdapter: JBluetoothAdapter;
    LFilter: JIntentFilter;
  begin
    LFilter := TJIntentFilter.JavaClass.init;
    LFilter.addAction(TJBluetoothAdapter.JavaClass.ACTION_DISCOVERY_FINISHED);
    LFilter.addAction(TJBluetoothDevice.JavaClass.ACTION_FOUND);
    SharedActivity.registerReceiver(FBroadcastReceiver, LFilter);
    Log.d('registered ACTION_FOUND and DISCOVERY_FINISHED');
 
    Log.d('Enabling discovery');
    BluetoothAdapter := TJBluetoothAdapter.JavaClass.getDefaultAdapter;
    if BluetoothAdapter.isDiscovering then
      BluetoothAdapter.cancelDiscovery;
    while BluetoothAdapter.isDiscovering do
      Sleep(10);
    BluetoothAdapter.startDiscovery;
    Log.d('Discovery enabled!');
  end);
end;

And that's it!