📄 bluetooth.java
字号:
//#ifdef useBT
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
import javax.bluetooth.*;
import java.util.Vector;
//#endif
class BlueTooth
{
//#ifdef useBT
// Bluetooth/JSR82 variables
private LocalDevice localDevice = null; // Reference to LocalDevice
private int previousDiscoverabilityMode = -1; // Used to restore discoverabilty mode afterwards
static public final boolean CONCEPT_SDK_BUILD = false;
// Attribute ID for service name for base language
static private final int SERVICE_NAME_BASE_LANGUAGE = 0x0100;
// The major device class (in CoD) used for phones:
static private final int MAJOR_DEVICE_CLASS_PHONE = 0x0200;
// Search types
/** Searches each device for the service. If a device with the service is found
* the search is cancelled. A connection is setup to that device/service.
* No device is shown to the user. */
static public final int SEARCH_CONNECT_FIRST_FOUND = 1;
/** Searches each device for the service. All devices with the searched service
* will be connected. No devices are shown to the user. */
static public final int SEARCH_CONNECT_ALL_FOUND = 2;
/** Searches for the service on every found device. A list of devices that
* offer the service is displayed to the user. User can stop the service
* search if at least one device has been found. After stop or after all
* devices are shown to the user the user can select one device. This
* device is connected. */
static public final int SEARCH_ALL_DEVICES_SELECT_ONE = 3;
/** Searches for the service on every found device. A list of devices that
* offer the service is displayed to the user. User can stop the service
* search if at least one device has been found. After stop or after all
* devices are shown to the user the user can select one or several devices. These
* devices are connected.
* Note that this functionality is only available on devices which support
* point-to-multipoint connectivity (bluetooth.connected.devices.max > 1). If the
* device supports only point-to-point connectivity (bluetooth.connected.devices.max = 1) the behaviour is the same as
* if SEARCH_ALL_DEVICES_SELECT_ONE would have been used.
*/
static public final int SEARCH_ALL_DEVICES_SELECT_SEVERAL = 4;
// UUID:
// x = random, b = BD address of one of my Bluetooth devices (because BD addresses are also unique)
// xxxx xxxx xxxx 1xxx 8xxx bbbbbbbbbbbb
// Eg. for my device = 006057028C19, ie. "00000000000010008000006057028C19"
private String serviceUUID = "20000000000010008000006057028C19";
private String localName = null; // The name of the device/service
private String warning; // Warnign presented to the user in case no device or no service was found
private static BluetoothConnection[] btConnections; // All Bluetooth connections
private StreamConnectionNotifier notifier; // For the server
private Vector urlStrings; // This holds the url strings of the returned services
private DeviceList deviceList; // List with devices that is shown to the user.
private DiscoveryAgent discoveryAgent; // Reference to DiscoveryAgent (used for Inquiry)
private Listener listener; // Discovery Listener (used for inquiry)
private Vector foundServiceRecords; // holds all the found service records
private int searchType; // Holds the search type the user wants to use
private int serviceSearchTransId; // trans action id for current service search, if there is no serv search this is -1
private int maxDevices; // Number of max. connectable devices (retrieved by getproperty)
public static StringBuffer ErrorMessage = new StringBuffer("");
// Used for waiting/notify
private Object block_c; // for Client
private Object block_s; // for Server
private Object block_r; // for Server
private Object block_ss; // for termination of service search
private Object block_notifier; // For Notifier.close
public static int lastSent;
public static int gotInt;
public static boolean bReadReady;
public static boolean recThread;
//#endif
public static boolean ConnectCancelled = false;
public static boolean gameFound;
BlueTooth()
{
//#ifdef useBT
//System.out.println("BTHere1");
try
{
// Create object used to synchronize/lock
block_r = new Object();
block_c = new Object();
block_s = new Object();
block_ss = new Object();
block_notifier = new Object();
// Obtain local device object
localDevice = LocalDevice.getLocalDevice();
//System.out.println("BTHere2");
// Retrieve number of connectable devices
maxDevices = Integer.parseInt( LocalDevice.getProperty( "bluetooth.connected.devices.max" ) );
//System.out.println("BTHere3");
// Because of definition with parked devices
if( maxDevices > 2 )
{ // limit to 2
maxDevices = 2;
}
}
catch(Exception e)
{ // not much that can be done
localDevice = null;
ErrorMessage.append("Error trying to get local device properties: ");
ErrorMessage.append(e.getMessage());
return;
// ErrorScreen.showError(message, display.getCurrent());
}
// Set UUID
//System.out.println("BTHere4");
//setServiceUUID( "20000000000010008000006057028C19" );
// Check if Bluetooth is turned on
String name;
try
{
name = LocalDevice.getLocalDevice().getFriendlyName();
//System.out.println("BTHere5");
}
catch( BluetoothStateException e )
{ // display user notification
ErrorMessage.append("Please switch Bluetooth on!");
return;
}
//System.out.println("BTHere6");
// Sets the name how this device is shown to the remote user
setName( name );
//#endif
}
public static boolean isConnected()
{
//#ifdef useBT
try
{
if (btConnections[0] == null) return false;
if (BlueTooth.btConnections[0].isClosed()) return false;
}
catch (Exception e)
{
return false;
}
//#endif
return true;
}
public int retrieve()
{
int inp = 0;
//#ifdef useBT
inp = BlueTooth.gotInt;
if (!bReadReady)
{
bReadReady = true;
synchronized( block_r )
{
block_r.notify();
}
}
//#endif
return inp;
}
public static void send(int c)
{
//#ifdef useBT
try
{
lastSent = c;
btConnections[0].writeInt(c);
}
catch( IOException e )
{ // If error, then close
// btConnections[0].close();
// Check if all connections are closed
// if( checkIfAllClosed() )
{ // all closed -> return
// return;
//System.out.println("Send Error");
}
}
catch (Exception e)
{
}
//#endif
}
public static void resend()
{
//#ifdef useBT
send(lastSent);
//#endif
}
public void startReceive()
{
//#ifdef useBT
recThread = true;
// Start Server
ReceiveThread rt = new ReceiveThread(0);
rt.start();
//#endif
}
public void hostGame()
{
//#ifdef useBT
initGame();
// Start Server
ServerThread st = new ServerThread();
st.start();
//#endif
}
public void joinGame()
{
//#ifdef useBT
initGame();
ClientThread ct = new ClientThread( SEARCH_CONNECT_FIRST_FOUND );
ct.start();
//#endif
}
private static void initGame()
{
//#ifdef useBT
ConnectCancelled = false;
lastSent = 0;
gotInt = -1;
bReadReady = false;
recThread = false;
gameFound = false;
//#endif
}
public void interuptServer(boolean bHost)
{
//#ifdef useBT
try
{
if (bHost)
{
synchronized( block_s )
{
block_s.notify();
}
}
else
{
synchronized( block_c )
{
block_c.notify();
}
}
}
catch (Exception e)
{
ErrorMessage.append("XXX");
ErrorMessage.append(e);
//System.out.println("interuptServer Error " + e.getMessage());
}
//#endif
}
//#ifdef useBT
// Innerclass
/** The ServerThread is used to wait until someone connects. <br
* A thread is needed otherwise it would not be possible to display
* anything to the user.
*/
private class ServerThread
extends Thread
{
/**
* This method runs the server.
*/
public void run()
{
//System.out.println("BTHere7");
try
{
// Wait on client
BluetoothConnection[] con = waitOnConnection();
//System.out.println("BTHere8");
if( con[0] == null )
{ // Connection cancelled
ErrorMessage.append("Connection Cancelled.");
ConnectCancelled = true;
//System.out.println("BTHere9 Cancelled");
}
else
{
gameFound = true;
//System.out.println("BTHere9 Connection OK -");
}
// Create Canvas to display keystrokes
// nc = new NumberCanvas( con );
// Set as new display
// display.setCurrent( nc );
}
catch (BluetoothStateException e)
{
//System.out.println("BTHere10 BluetoothStateException " + e.getMessage());
ConnectCancelled = true;
}
catch (IOException e)
{
//System.out.println("BTHere10 IOException " + e.getMessage());
ConnectCancelled = true;
}
catch( InterruptedException e )
{ // display error message
ErrorMessage.append("Error:");
ErrorMessage.append(e.getMessage());
//System.out.println("BTHere10 " + e.getMessage());
ConnectCancelled = true;
return;
}
catch (Exception e)
{
//System.out.println("BTHere10 Exception " + e.getMessage());
ConnectCancelled = true;
}
}
}
private class ClientThread
extends Thread
{
// Search type
private int searchType;
/** Constructor
* @param st The search type. Possible values:
* {@link BluetoothDiscovery.SEARCH_CONNECT_FIRST_FOUND SEARCH_CONNECT_FIRST_FOUND},
* {@link BluetoothDiscovery.SEARCH_CONNECT_ALL_FOUND SEARCH_CONNECT_ALL_FOUND},
* {@link BluetoothDiscovery.SEARCH_ALL_DEVICES_SELECT_ONE SEARCH_ALL_DEVICES_SELECT_ONE},
* {@link BluetoothDiscovery.SEARCH_ALL_DEVICES_SELECT_SEVERAL SEARCH_ALL_DEVICES_SELECT_SEVERAL}.
*/
protected ClientThread( int st )
{
// store search type
searchType = st;
}
/**
* This method runs the client.
*/
public void run()
{
try
{
BluetoothConnection conn[] = searchService( searchType );
if( conn.length != 0 )
{
gameFound = true;
//System.out.println("Join Game Connection OK -");
}
else
{ // nothing found
ConnectCancelled = true;
//System.out.println("Join Game Connection Not OK -");
}
//System.out.println("Join Game Connection Done -");
}
catch( Exception e )
{ // display error message
ErrorMessage.append("Error:");
ErrorMessage.append(e.getMessage());
//System.out.println("ClientThread Exception " + e.getMessage());
ConnectCancelled = true;
return;
}
}
}
/** Closes the Notifier.
* If Notifier is not null, Notifier.close is called . Afterwards
* Notifier is set to null.
*/
private void closeNotifier()
{
synchronized( block_notifier )
{
if( notifier != null )
{
try
{
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -