Help Center

Local Navigation

Use a Bluetooth serial port connection

You can use the Bluetooth® API (net.rim.device.api.bluetooth) to let your BlackBerry® device application access the Bluetooth Serial Port Profile and initiate a server or client Bluetooth serial port connection to a computer or other Bluetooth enabled device.

  1. Import the following classes:
    • javax.microedition.io.Connector
    • net.rim.device.api.bluetooth.BluetoothSerialPort
    • java.io.DataOutputStream
    • java.io.DataInputStream
    • java.lang.String
    • java.io.IOException
  2. Import the javax.microedition.io.StreamConnection interface.
  3. Invoke Connector.open(), providing the serial port information that BluetoothSerialPort.getSerialPortInfo() returns as a parameter to open a Bluetooth connection.
    BluetoothSerialPortInfo[] info = BluetoothSerialPort.getSerialPortInfo();
    StreamConnection _bluetoothConnection = (StreamConnection)Connector.open( info[0].toString(), Connector.READ_WRITE );
    
  4. To send data on the Bluetooth connection, invoke openDataOutputStream() or openOutputStream().
    DataOutputStream _dout = _bluetoothConnection.openDataOutputStream();
  5. Use the write methods on the output stream to write data.
    private static final int JUST_OPEN = 4;
    _dout.writeInt(JUST_OPEN);
  6. To receive data on the Bluetooth connection, in a non-main event thread, invoke openInputStream() or openDataInputStream(). Use the read methods on the input stream to read the data.
    DataInputStream _din = _bluetoothConnection.openDataInputStream();
    String contents = _din.readUTF();
  7. Invoke close()on the input and output streams, and on the Bluetooth serial port connection object to close the Bluetooth connection. The close() method can throw IOExceptions. Make sure the BlackBerry device application implements exception handling.
    if (_bluetoothConnection != null) {
    try {
         _bluetoothConnection.close();
        } catch(IOException ioe) {
          }
    }
    
    if (_din != null) {
    try {
         _din.close();
         } catch(IOException ioe) {
           }
    }
    
    if (_dout != null) {
    try {
         _dout.close();
        } catch(IOException ioe) {
          }
    }
    
    _bluetoothConnection = null;
    _din = null;
    _dout = null;
Next topic: Wi-Fi connections

Was this information helpful? Send us your comments.