connect Bluetooth and Write data - Android Bluetooth

Android examples for Bluetooth:Bluetooth Data Transfer

Description

connect Bluetooth and Write data

Demo Code



//package com.java2s;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.List;
import java.util.UUID;

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

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 connectWriteBlocos(BluetoothDevice device, final List<String[]> nota) {
    BluetoothAdapter mBTAdapter = BluetoothAdapter.getDefaultAdapter();
    BluetoothDevice mBTDevice = mBTAdapter.getRemoteDevice(device.getAddress());
    BluetoothSocket mBTSocket;/*  w  w w .j  a va 2 s . c o m*/
    try {
      mBTSocket = mBTDevice.createRfcommSocketToServiceRecord(UUID_RFCOMM_GENERIC);
      mBTSocket.connect();
      OutputStream mBTOutputStream = mBTSocket.getOutputStream();

      mBTOutputStream.write(nota.get(0)[0].getBytes());
      for (int i = 0; i < nota.get(1).length; i++) {
        mBTOutputStream.write(nota.get(1)[i].getBytes());
      }

      mBTOutputStream.write(nota.get(2)[0].getBytes());
      Thread.sleep(12000 + (nota.get(1).length * 8000));

      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 {
      Log.i("Log", "service metohd is called ");
      Class cl = Class.forName("android.bluetooth.BluetoothDevice");
      Class[] par = {};
      Method method = cl.getMethod("createBond", par);
      Object[] args = {};
      bool = (Boolean) method.invoke(bdDevice);
    } catch (Exception e) {
      Log.i("Log", "Inside catch of serviceFromDevice Method");
      e.printStackTrace();
    }
    return bool.booleanValue();
  }
}

Related Tutorials