About the author
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!