Java Reference
In-Depth Information
The discovery process callback methods are also supplied with a
transaction identifier that can be used to stop an active service discovery
process by passing this to the cancelServiceSearch() method of
the DiscoveryAgent class.
Once devices and services have been located and queried, we are
ready to open a connection. As already mentioned, setting up a Bluetooth
connection can be a little confusing at first because, unlike in other
networking scenarios, connections are initiated by the server rather
than the client. To make sure that our design remains clean, we've
defined an observer interface that is notified whenever our Bluetooth
state changes:
public interface IBluetoothObserver {
public void notifyStateChange(int newState);
public void notifyMessageReceived(String message);
}
In Figure 8.5, note that the GameController class implements the
IBluetoothObserver interface shown above. Using an observer is
good practice as it keeps UI-related code separate from Bluetooth man-
agement code.
The listing below shows the states that are defined in the Bluetooth-
Manager class for this game. You can see that each state change notifies
the registered observer instance in the setState() method:
// states
public static final int IDLE
= 0;
public static final int DETECTING_BLUETOOTH
= 1;
public static final int BLUETOOTH_ENABLED
= 2;
public static final int BLUETOOTH_DISABLED
= 3;
public static final int FINDING_DEVICES
= 4;
public static final int FINDING_SERVICES
= 5;
public static final int WAITING
= 6;
public static final int CONNECTING
= 7;
public static final int CONNECTED
= 8;
public static final int CONNECTION_FAILED
= 9;
public static final int CANCELLING
= 10;
public static final int DISCONNECTED
= 11;
// called on state transitions
private void setState(int state) {
this.state = state;
observer.notifyStateChange(state);
}
It is the slave (client) that opens a server socket and waits for a
connection request from the master as illustrated in the code snippet
below taken from the BluetoothManager class in our sample game:
Search WWH ::




Custom Search