Java Reference
In-Depth Information
String SERVICE_URL = "btspp://localhost:" + SERVICE_UUID;
private void startClientMode() {
...
// advertise that we have the game
String clientName = localDevice.getFriendlyName();
String url = SERVICE_URL + ";name=" + clientName;
...
notifier = (StreamConnectionNotifier) Connector.open(url);
// wait for server-initiated connection
connection = (StreamConnection) notifier.acceptAndOpen();
// get I/O streams
inputStream = connection.openInputStream();
outputStream = connection.openOutputStream();
...
// notify our Bluetooth observer that we are connected
setState(CONNECTED);
Since the master device has already run an inquiry for devices and
discovered their available services, all that remains is for the master
to initiate a connection to the remote device (the slave). Bluetooth
addresses are cumbersome and change frequently so the master uses the
getConnectionUrl() method of a remote device's ServiceRecord
to determine how to open a connection to it:
private void startServerMode() {
...
ServiceRecord serviceRecord;
...
// specify connection settings
int security = ServiceRecord.NOAUTHENTICATE_NOENCRYPT;
boolean mustBeMaster = false;
// determine url to use given above
String url = serviceRecord.getConnectionURL(security, mustBeMaster);
// initiate the connection
connection = (StreamConnection) Connector.open(url);
// get I/O streams
inputStream = connection.openInputStream();
outputStream = connection.openOutputStream();
// notify our Bluetooth observer that we are connected
setState(CONNECTED);
Once connections have been established you can use normal read and
write methods to send data between the connected handsets. In Finding
Higgs , we have kept data transfers minimal as the main point of them is
simply to keep each player aware of the other player's current score.
Of particular interest, however, is that in this case we want the game
on each handset to start at the same time (as closely as possible) since
it's only a one-minute game and it's far less fun when your opponent
finishes five seconds before you do because they started five seconds
earlier. To achieve this, we wait until each device is connected, show the
game screen (which may be faster on more powerful hardware) and then
Search WWH ::




Custom Search