Learn Java

Remote Device Discovery

Example in this section can be found in my Github Repo.

Demo

Run RemoteDeviceDiscovery with command:

java -cp classes/:../jars/bluecove-2.1.0.jar:../jars/bluecove-gpl-2.1.0.jar RemoteDeviceDiscovery

Result:

java -cp classes/:../jars/bluecove-2.1.0.jar:../jars/bluecove-gpl-2.1.0.jar RemoteDeviceDiscovery
BlueCove version 2.1.0 on bluez
wait for device inquiry to complete...
Device E0B9A568A098 found
     name OPAS-NB
Device Inquiry completed!
1 device(s) found
BlueCove stack shutdown completed

Explains

discovery/src/RemoteDeviceDiscovery.java:

    public static void main(String[] args) throws IOException, InterruptedException {

        final Object inquiryCompletedEvent = new Object(); 

        devicesDiscovered.clear();

        DiscoveryListener listener = new DiscoveryListener() {
            public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod){/*Implement*/}
            public void inquiryCompleted(int discType) { /*Implement*/ }
            public void serviceSearchCompleted(int transID, int respCode) {}
            public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {}
        };

        synchronized(inquiryCompletedEvent) {
            boolean started = LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC, listener);
            /*Implement*/ 
        }
    }

Process

  1. inquiryCompletedEvent is a lock.
  2. Use LocalDevice.getDiscoveryAgent() to get an instance of DiscoveryAgent, which can discover remote bluetooth device.
  3. Use DiscoveryAgent.startInquiry() to find remote device.
  4. When each device is found, DiscoveryListener.deviceDiscovered is called. When the query is finished, DiscoveryListener.inquiryCompleted() is called.

API

  1. LocalDevice:

    The LocalDevice class defines the basic functions of the Bluetooth manager. The Bluetooth manager provides the lowest level of interface possible into the Bluetooth stack. It provides access to and control of the local Bluetooth device.

    This class produces a singleton object.

    • static LocalDevice getLocalDevice()
    • public DiscoveryAgent getDiscoveryAgent()
  2. DiscoveryAgent

    The DiscoveryAgent class provides methods to perform device and service discovery. A local device must have only one DiscoveryAgent object. This object must be retrieved by a call to getDiscoveryAgent() on the LocalDevice object.

    • public boolean startInquiry(int accessCode, DiscoveryListener listener) throws BluetoothStateException
  3. DiscoveryListener

    • void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod)
    • void servicesDiscovered(int transID, ServiceRecord[] servRecord)
    • void serviceSearchCompleted(int transID, int respCode)
    • void inquiryCompleted(int discType)