connect to Bluetooth Device Write byte array - Android android.bluetooth

Android examples for android.bluetooth:Bluetooth

Description

connect to Bluetooth Device Write byte array

Demo Code

import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;

import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Build;

public class Main {

  static final UUID UUID_RFCOMM_GENERIC = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

  @TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1)
  public static boolean connectWrite(BluetoothDevice device, byte[] text, int delay) {
    BluetoothAdapter mBTAdapter = BluetoothAdapter.getDefaultAdapter();
    BluetoothDevice mBTDevice = mBTAdapter.getRemoteDevice(device.getAddress());
    BluetoothSocket mBTSocket;/*  w w w  .  j a  v  a 2  s  .  c o  m*/
    try {
      mBTSocket = mBTDevice.createInsecureRfcommSocketToServiceRecord(UUID_RFCOMM_GENERIC);
      mBTSocket.connect();
      OutputStream mBTOutputStream = mBTSocket.getOutputStream();
      mBTOutputStream.write(text);
      mBTOutputStream.flush();
      Thread.sleep(delay);
      mBTOutputStream.close();
      return true;
    } catch (Exception e1) {
      e1.printStackTrace();
      return false;
    }
  }

  @SuppressWarnings({ "unchecked", "rawtypes", "unused" })
  public static Boolean connect(BluetoothDevice bdDevice) {
    Boolean bool = false;
    try {
      Class cl = Class.forName("android.bluetooth.BluetoothDevice");
      Class[] par = {};
      Method method = cl.getMethod("createBond", par);
      Object[] args = {};
      bool = (Boolean) method.invoke(bdDevice);// , args);// this invoke creates the detected devices paired.
    } catch (Exception e) {
      e.printStackTrace();
    }
    return bool.booleanValue();
  }

}

Related Tutorials