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:
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!
In 2017, with the release of Delphi 10.2 Tokyo, Embarcadero introduced a specialized implementation of the Observer pattern into the System.Classes unit. While it has been in the wild for 9 years, it remains a "hidden" architecture for many, primarily because it serves as the invisible engine behind LiveBindings. Other than live bindings, you can also use the Observer pattern as a way to update component settings to the Windows registry, an .ini file, or persist it elsewhere.
System.Classes