My question isn’t specific to Java but that is the language I’m using to achieve what I want.
I’m experimenting with Bluetooth in Java and have written a simple terminal program i.e. no GUI interface that searches for nearby Bluetooth devices and lists them. My code is as follows:
import javax.bluetooth.*;
public class BluetoothTest implements DiscoveryListener{
private static boolean isAlive = true;
public static void main(String[] args) {
try {
LocalDevice ld = LocalDevice.getLocalDevice();
if (LocalDevice.isPowerOn()){
System.out.println("Power On.");
System.out.println("Friendly Name: " + ld.getFriendlyName());
System.out.println("Address: " + ld.getBluetoothAddress());
DiscoveryAgent da = ld.getDiscoveryAgent();
da.startInquiry(DiscoveryAgent.GIAC,new BluetoothTest());
while (isAlive){
/* Sleep */
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
System.out.println("Power Off.");
}
} catch (BluetoothStateException e) {
System.out.println(e.toString());
}
}
public void setAlive(boolean status){
isAlive = status;
}
public void deviceDiscovered(RemoteDevice rd, DeviceClass dc){
try{
System.out.println(rd.getFriendlyName(true));
} catch (java.io.IOException e){
System.out.println(e.toString());
}
}
public void inquiryCompleted(int discType){
isAlive = false;
}
public void servicesDiscovered(int transID, ServiceRecord[] sr){
}
public void serviceSearchCompleted(int transID, int respCode){
}
}
The startInquiry() of DiscoveryAgent object returns immediately and any devices that are discovered are returned to the DiscoveryListener interface which I have implemented. The problem is unless I include the while() loop the program will terminate before any devices are discovered.
Just how do applications efficiently stay resident? Is it achieved by having a separate ‘working’ thread and a main thread which spawns the working thread but itself sleeps until the worker had finished?
You may use Object wait / notify mechanism to hold main method until BluetoothTest notifies on a common object lock.
Just a pseudo code,
Define a static final Object _mutex = new Object();
In main method after call of startInquiry call _mutex.wait(); This will hold the main thread.
In inquiryCompleted call _mutex.notify(); This will release the main thread.
Please note that this code will work only if startInquiry create a new thread and invokes call back methods. I am not much aware of DiscoverAgent class. So if that’s not the case, the above solution might now work.