Code example for BluetoothSocket

Methods: connect, getInputStream, getOutputStream, getRemoteDevice

0
 
  BluetoothSocket socket;
 
  BluetoothHelper(BluetoothSocket _socket)
    throws IOException { 
    super(_socket.getRemoteDevice().getAddress());
    socket = _socket;
 
    super.set(socket.getInputStream(), socket.getOutputStream());
  } 
 
  public void close() { 
    super.close(); 
 
    try { 
      socket.close();
    } catch (IOException e) {
      /* ignore... what else should we do if closing the socket 
         fails? */ 
    } 
  } 
 
  public int getBaudRate() { 
    return 19200; 
  } 
 
  public boolean setBaudRate(int baudRate) {
    return true; 
  } 
 
  public static String[] list() {
    if (adapter == null)
      return null; 
 
    Set<BluetoothDevice> devices = adapter.getBondedDevices();
    if (devices == null)
      return null; 
 
    String[] addresses = new String[devices.size() * 2];
    int n = 0;
    for (BluetoothDevice device: devices) {
      addresses[n++] = device.getAddress();
      addresses[n++] = device.getName();
    } 
 
    return addresses;
  } 
 
  public static BluetoothHelper connect(String address) {
    if (adapter == null)
      return null; 
 
    try { 
      BluetoothDevice device = adapter.getRemoteDevice(address);
      if (device == null)
        return null; 
 
      BluetoothSocket socket =
        device.createRfcommSocketToServiceRecord(THE_UUID);
      socket.connect();
      return new BluetoothHelper(socket);
    } catch (Exception e) {
      Log.e(TAG, "Failed to connect to Bluetooth: " + e.getMessage());
      return null; 
    }