安卓(Android) 怎么连接蓝牙并写入数据

2019年10月22日21:08:29安卓(Android) 怎么连接蓝牙并写入数据已关闭评论 267 1708字阅读5分41秒

1.简介

安卓(Android) 怎么连接蓝牙并写入数据?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */



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;
    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();
  }
}

 
继续阅读
编程十万个怎么办