📄 bluetoothdiscovery.java
字号:
* NextDeviceServiceSearch.
* Retrieves the next device from the stored list and searches
* for the Service on this device.
*/
private void nextDeviceServiceSearch()
{
UUID[] u = new UUID[1];
u[0] = new UUID( serviceUUID, false );
int attrbs[] =
{ SERVICE_NAME_BASE_LANGUAGE }; // Retrieved service record should include service name
RemoteDevice dev;
// Update progress bar
((PageProgressBar)progressBar).nextDevice();
// Retrieve next device
try
{
dev = (RemoteDevice) cached_devices.firstElement();
cached_devices.removeElementAt( 0 );
}
catch( Exception e )
{ // All devices searched
if( foundServiceRecords.size() == 0 )
{ // If no device found then alert to user
warning = "No service found!";
}
// If service not found on any device return to main,
// also if SEARCH_CONNECT_ALL_FOUND was selected.
if( (foundServiceRecords.size() == 0)
| (searchType == SEARCH_CONNECT_ALL_FOUND) )
{ // return to main function
synchronized( block_c )
{
block_c.notifyAll();
}
}
// If deviceList is used, then it's ready now (will change "Stop"
// button into "Cancel".
if( deviceList != null )
{
deviceList.ready();
}
return;
}
// search for the service
try
{
currServRec = null;
serviceSearchTransId = discoveryAgent.searchServices( attrbs, u, dev, listener );
}
catch( BluetoothStateException e )
{
// an error occured
// Try next device
nextDeviceServiceSearch();
}
}
/** Is called when the service we searched for is found.
*
* @param transID the transaction ID of the service search that is posting the result.
* @param servRecord The service we searched for.
*/
public void servicesDiscovered( int transID, ServiceRecord[] servRecord )
{
// A Service was found on the device.
currServRec = servRecord[0];
}
/** Depending on the search type different actions are taken.
* Possible search types are:<br>
* {@link #SEARCH_CONNECT_FIRST_FOUND SEARCH_CONNECT_FIRST_FOUND},<br>
* {@link #SEARCH_CONNECT_ALL_FOUND SEARCH_CONNECT_ALL_FOUND},<br>
* {@link #SEARCH_ALL_DEVICES_SELECT_ONE SEARCH_ALL_DEVICES_SELECT_ONE}, and<br>
* {@link #SEARCH_ALL_DEVICES_SELECT_SEVERAL SEARCH_ALL_DEVICES_SELECT_SEVERAL}.
* See also {@link #searchService searchService}.
* @param transID the transaction ID of the service search that is posting the result.
* @param respCode a code showing how the service search was completed
*/
public void serviceSearchCompleted( int transID, int respCode )
{
synchronized( block_ss )
{
// Reset trans action id
serviceSearchTransId = -1;
// Collect all devices with right service
if( currServRec != null )
{ // A device with this service is found, so add it
foundServiceRecords.addElement( currServRec );
urlStrings.addElement( currServRec.getConnectionURL( ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false ) );
}
switch( searchType )
{
case SEARCH_CONNECT_FIRST_FOUND:
// Stop searching after first device with the service is found
if( currServRec != null )
{ // A device with this service is found, so stop
synchronized( block_c )
{
block_c.notifyAll();
}
return;
}
break;
case SEARCH_CONNECT_ALL_FOUND:
break;
case SEARCH_ALL_DEVICES_SELECT_ONE:
case SEARCH_ALL_DEVICES_SELECT_SEVERAL:
if( currServRec != null )
{ // Update displayed list
displayFoundServices();
}
break;
}
// Check if service search was terminated
if( respCode == SERVICE_SEARCH_TERMINATED )
{ // Notify the terminator (cancelServSearch)
synchronized( block_ss )
{
block_ss.notifyAll();
}
}
else
{ // Search next device
nextDeviceServiceSearch();
}
}
}
/**
* displayFoundServices
* Updates the displayed found services.
*/
private void displayFoundServices()
{
if( deviceList == null )
{ // Create new device list
int lt;
if( searchType == SEARCH_ALL_DEVICES_SELECT_SEVERAL )
{
lt = List.MULTIPLE;
}
else
{
lt = List.IMPLICIT;
}
// Create new device lsit
deviceList = new DeviceList( lt );
}
// Append new service/device
// Retrieve remote name
DataElement de = ((ServiceRecord)foundServiceRecords.lastElement()).getAttributeValue( SERVICE_NAME_BASE_LANGUAGE );
String rname = (String) de.getValue();
// Add device to list
deviceList.append( rname, null );
}
}
// Inner class
/**
* waitOnServSearchTermination
* Only required in case a service search was cancelled, before at least
* one service was found.
* Waits until serviceSearchCompleted is called and then
* notifies the searchServices method.
*/
private class waitOnServSearchTermination
extends Thread
{
/**
* Terminates service search.
* Waits until serviceSearchCompleted is called and then
* notifies the searchServices method.
*/
public void run()
{
synchronized( block_ss )
{
if( serviceSearchTransId != -1 )
{ // only if there is a service search active
discoveryAgent.cancelServiceSearch( serviceSearchTransId );
// wait until service search has terminated
try
{
block_ss.wait();
}
catch(InterruptedException e)
{
// We can ignore this
}
// Now notify searchService method
synchronized( block_c )
{
block_c.notifyAll();
}
}
}
}
}
/**
* DeviceList is a List to display the found devices.
*/
private class DeviceList
extends List
implements CommandListener
{
// The possible commands
private Command ok;
private Command stop;
private Command cancel;
/** Constructor of DeviceList
* @param list_type determines the type of list. Either MULTIPLE or IMPLICIT.
*/
public DeviceList( int list_type )
{
super( "Select:", list_type );
// Set text wrap around
setFitPolicy( Choice.TEXT_WRAP_ON );
// Create commands
ok = new Command( "OK", Command.OK, 1 );
stop = new Command( "Stop", Command.STOP, 1 );
cancel = new Command( "Cancel", Command.CANCEL, 1 );
// append commands
addCommand( ok );
addCommand( stop );
setCommandListener( this );
display.setCurrent( this );
}
/**
* Cancels the current service search.
*/
private void cancelServSearch()
{
synchronized( block_ss )
{
if( serviceSearchTransId != -1 )
{ // only if there is a service search active
discoveryAgent.cancelServiceSearch( serviceSearchTransId );
// wait until service search has terminated
try
{
block_ss.wait();
}
catch( InterruptedException e )
{
// we can ignore this
}
}
}
}
/**
* Should be called when no more elements will be added to the
* list.
* The "Stop" button will change into "Cancel".
*/
public void ready()
{
removeCommand( stop );
addCommand( cancel );
}
/**
* Respond to commands.
* @param c The command.
* @param s The displayable object. */
public void commandAction( Command c, Displayable s )
{
int com = c.getCommandType();
if( (c == SELECT_COMMAND) && (searchType == SEARCH_ALL_DEVICES_SELECT_ONE) )
{ // Behave the same as if OK was pressed.
com = Command.OK;
}
switch( com )
{
case Command.OK:
// User selected OK
// Cancel the current service search.
cancelServSearch();
// Remove all elements that are not selected
for( int i=size()-1; i>=0; i-- )
{
if( ! isSelected(i) )
{ // not selected then remove
urlStrings.removeElementAt(i);
}
}
// return to searchService function
synchronized( block_c )
{
block_c.notifyAll();
}
break;
case Command.STOP:
// User stopped
// Cancel the current service search.
cancelServSearch();
// Exchange stop button with cancel button
ready();
break;
case Command.CANCEL:
// User cancelled
// Remove all elements
urlStrings.removeAllElements();
// return to main function
synchronized( block_c )
{
block_c.notifyAll();
}
break;
}
}
}
/** acceptAndOpenThread.
* This is needed as thread to allow cancellation from user interface.
* Thread just does an acceptAndOpen and waits until Exception is thrown
* eg. UI called Cancel or client connects.
* If a client connects a thread is started for that connection.
*/
private class acceptAndOpenThread
extends Thread
{
/**
* run method
* Start acceeptAndOpen and wait on Exception or connection.
*/
public void run()
{
StreamConnection con;
// Prepare data
btConnections = new BluetoothConnection[1];
// Register service
try
{
// Wait on client
con = (StreamConnection) notifier.acceptAndOpen();
btConnections[0] = new BluetoothConnection(con, localName, "Host");
// Read host name
String remoteName = btConnections[0].readString();
btConnections[0].setRemoteName( remoteName );
}
catch(Exception e)
{
// Accept and open terminated abnormally (maybe cancel)
btConnections[0] = null;
}
// Remove notifier
closeNotifier();
// wakeup
synchronized( block_s )
{
block_s.notifyAll();
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -