分享Android 蓝牙4.0(ble)开发的解决方案_Android

最近,随着智能穿戴式设备、智能医疗以及智能家居的普及,蓝牙开发在移动开中显得非常的重要。由于公司需要,研究了一下,蓝牙4.0在Android中的应用。

以下是我的一些总结。

1.先介绍一下关于蓝牙4.0中的一些名词吧:   
(1)、GATT(Gneric Attibute  Profile)

通过ble连接,读写属性类小数据Profile通用的规范。现在所有的ble应用Profile  都是基于GATT
(2)、ATT(Attribute Protocal)
GATT是基于ATT Potocal的ATT针对BLE设备专门做的具体就是传输过程中使用尽量少的数据,每个属性都有个唯一的UUID,属性chartcteristics and Service的形式传输。

(3)、Service是Characteristic的集合。
(4)、Characteristic 特征类型。

比如,有个蓝牙ble的血压计。他可能包括多个Servvice,每个Service有包括多个Characteristic

注意:蓝牙ble只能支持Android 4.3以上的系统 SDK>=18

2.以下是开发的步骤:
2.1首先获取BluetoothManager 

复制代码 代码如下:

BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); 

2.2获取BluetoothAdapter

复制代码 代码如下:

BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter(); 

2.3创建BluetoothAdapter.LeScanCallback

private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { 

  @Override
  public void onLeScan(final BluetoothDevice device, int rssi, final byte[] scanRecord) { 

   runOnUiThread(new Runnable() {
    @Override
    public void run() {
     try {
      String struuid = NumberUtils.bytes2HexString(NumberUtils.reverseBytes(scanRecord)).replace("-", "").toLowerCase();
      if (device!=null && struuid.contains(DEVICE_UUID_PREFIX.toLowerCase())) {
       mBluetoothDevices.add(device);
      }
     } catch (Exception e) {
      e.printStackTrace();
     }
    }
   });
  }
 }; 

2.4.开始搜索设备。

复制代码 代码如下:

mBluetoothAdapter.startLeScan(mLeScanCallback); 

2.5.BluetoothDevice  描述了一个蓝牙设备 提供了getAddress()设备Mac地址,getName()设备的名称。
2.6开始连接设备

 /**
  * Connects to the GATT server hosted on the Bluetooth LE device.
  *
  * @param address
  *   The device address of the destination device.
  *
  * @return Return true if the connection is initiated successfully. The
  *   connection result is reported asynchronously through the
  *   {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
  *   callback.
  */
 public boolean connect(final String address) {
  if (mBluetoothAdapter == null || address == null) {
   Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
   return false;
  } 

  // Previously connected device. Try to reconnect. (先前连接的设备。 尝试重新连接)
  if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null) {
   Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
   if (mBluetoothGatt.connect()) {
    mConnectionState = STATE_CONNECTING;
    return true;
   } else {
    return false;
   }
  } 

  final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
  if (device == null) {
   Log.w(TAG, "Device not found. Unable to connect.");
   return false;
  }
  // We want to directly connect to the device, so we are setting the
  // autoConnect
  // parameter to false.
  mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
  Log.d(TAG, "Trying to create a new connection.");
  mBluetoothDeviceAddress = address;
  mConnectionState = STATE_CONNECTING;
  return true;
 }

2.7连接到设备之后获取设备的服务(Service)和服务对应的Characteristic。

// Demonstrates how to iterate through the supported GATT
// Services/Characteristics.
// In this sample, we populate the data structure that is bound to the
// ExpandableListView
// on the UI.
private void displayGattServices(List<BluetoothGattService> gattServices) {
 if (gattServices == null)
  return;
 String uuid = null;
 ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<>();
 ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData = new ArrayList<>(); 

 mGattCharacteristics = new ArrayList<>(); 

 // Loops through available GATT Services.
 for (BluetoothGattService gattService : gattServices) {
  HashMap<String, String> currentServiceData = new HashMap<>();
  uuid = gattService.getUuid().toString();
  if (uuid.contains("ba11f08c-5f14-0b0d-1080")) {//服务的uuid
   //System.out.println("this gattService UUID is:" + gattService.getUuid().toString());
   currentServiceData.put(LIST_NAME, "Service_OX100");
   currentServiceData.put(LIST_UUID, uuid);
   gattServiceData.add(currentServiceData);
   ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList<>();
   List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
   ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<>(); 

   // Loops through available Characteristics.
   for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
    charas.add(gattCharacteristic);
    HashMap<String, String> currentCharaData = new HashMap<>();
    uuid = gattCharacteristic.getUuid().toString();
    if (uuid.toLowerCase().contains("cd01")) {
     currentCharaData.put(LIST_NAME, "cd01");
    } else if (uuid.toLowerCase().contains("cd02")) {
     currentCharaData.put(LIST_NAME, "cd02");
    } else if (uuid.toLowerCase().contains("cd03")) {
     currentCharaData.put(LIST_NAME, "cd03");
    } else if (uuid.toLowerCase().contains("cd04")) {
     currentCharaData.put(LIST_NAME, "cd04");
    } else {
     currentCharaData.put(LIST_NAME, "write");
    } 

    currentCharaData.put(LIST_UUID, uuid);
    gattCharacteristicGroupData.add(currentCharaData);
   } 

   mGattCharacteristics.add(charas); 

   gattCharacteristicData.add(gattCharacteristicGroupData); 

   mCharacteristicCD01 = gattService.getCharacteristic(UUID.fromString("0000cd01-0000-1000-8000-00805f9b34fb"));
   mCharacteristicCD02 = gattService.getCharacteristic(UUID.fromString("0000cd02-0000-1000-8000-00805f9b34fb"));
   mCharacteristicCD03 = gattService.getCharacteristic(UUID.fromString("0000cd03-0000-1000-8000-00805f9b34fb"));
   mCharacteristicCD04 = gattService.getCharacteristic(UUID.fromString("0000cd04-0000-1000-8000-00805f9b34fb"));
   mCharacteristicWrite = gattService.getCharacteristic(UUID.fromString("0000cd20-0000-1000-8000-00805f9b34fb")); 

   //System.out.println("=======================Set Notification==========================");
   // 开始顺序监听,第一个:CD01
   mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD01, true);
   mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD02, true);
   mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD03, true);
   mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD04, true);
  }
 }
}

2.8获取到特征之后,找到服务中可以向下位机写指令的特征,向该特征写入指令。

public void wirteCharacteristic(BluetoothGattCharacteristic characteristic) { 

  if (mBluetoothAdapter == null || mBluetoothGatt == null) {
   Log.w(TAG, "BluetoothAdapter not initialized");
   return;
  } 

  mBluetoothGatt.writeCharacteristic(characteristic); 

 } 

2.9写入成功之后,开始读取设备返回来的数据。

private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
  @Override
  public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
   String intentAction;
   //System.out.println("=======status:" + status);
   if (newState == BluetoothProfile.STATE_CONNECTED) {
    intentAction = ACTION_GATT_CONNECTED;
    mConnectionState = STATE_CONNECTED;
    broadcastUpdate(intentAction);
    Log.i(TAG, "Connected to GATT server.");
    // Attempts to discover services after successful connection.
    Log.i(TAG, "Attempting to start service discovery:" + mBluetoothGatt.discoverServices()); 

   } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
    intentAction = ACTION_GATT_DISCONNECTED;
    mConnectionState = STATE_DISCONNECTED;
    Log.i(TAG, "Disconnected from GATT server.");
    broadcastUpdate(intentAction);
   }
  } 

  @Override
  public void onServicesDiscovered(BluetoothGatt gatt, int status) {
   if (status == BluetoothGatt.GATT_SUCCESS) {
    broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
   } else {
    Log.w(TAG, "onServicesDiscovered received: " + status);
   }
  }
  //从特征中读取数据
  @Override
  public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
   //System.out.println("onCharacteristicRead");
   if (status == BluetoothGatt.GATT_SUCCESS) {
    broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
   }
  }
  //向特征中写入数据
  @Override
  public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
   //System.out.println("--------write success----- status:" + status);
  } 

  /*
   * when connected successfully will callback this method this method can
   * dealwith send password or data analyze 

   *当连接成功将回调该方法
   */
  @Override
  public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
   broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
   if (characteristic.getValue() != null) { 

    //System.out.println(characteristic.getStringValue(0));
   }
   //System.out.println("--------onCharacteristicChanged-----");
  } 

  @Override
  public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { 

   //System.out.println("onDescriptorWriteonDescriptorWrite = " + status + ", descriptor =" + descriptor.getUuid().toString()); 

   UUID uuid = descriptor.getCharacteristic().getUuid();
   if (uuid.equals(UUID.fromString("0000cd01-0000-1000-8000-00805f9b34fb"))) {
    broadcastUpdate(ACTION_CD01NOTIDIED);
   } else if (uuid.equals(UUID.fromString("0000cd02-0000-1000-8000-00805f9b34fb"))) {
    broadcastUpdate(ACTION_CD02NOTIDIED);
   } else if (uuid.equals(UUID.fromString("0000cd03-0000-1000-8000-00805f9b34fb"))) {
    broadcastUpdate(ACTION_CD03NOTIDIED);
   } else if (uuid.equals(UUID.fromString("0000cd04-0000-1000-8000-00805f9b34fb"))) {
    broadcastUpdate(ACTION_CD04NOTIDIED);
   }
  } 

  @Override
  public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
   //System.out.println("rssi = " + rssi);
  }
 }; 

 ----------------------------------------------
  //从特征中读取数据
  @Override
  public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
   //System.out.println("onCharacteristicRead");
   if (status == BluetoothGatt.GATT_SUCCESS) {
    broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
   }
  } 

2.10、断开连接

/**
  * Disconnects an existing connection or cancel a pending connection. The
  * disconnection result is reported asynchronously through the
  * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
  * callback.
  */
 public void disconnect() {
  if (mBluetoothAdapter == null || mBluetoothGatt == null) {
   Log.w(TAG, "BluetoothAdapter not initialized");
   return;
  }
  mBluetoothGatt.disconnect();
 }

2.11、数据的转换方法

// byte转十六进制字符串
 public static String bytes2HexString(byte[] bytes) {
  String ret = "";
  for (byte aByte : bytes) {
   String hex = Integer.toHexString(aByte & 0xFF);
   if (hex.length() == 1) {
    hex = '0' + hex;
   }
   ret += hex.toUpperCase(Locale.CHINA);
  }
  return ret;
 }
/**
  * 将16进制的字符串转换为字节数组
  *
  * @param message
  * @return 字节数组
  */
 public static byte[] getHexBytes(String message) {
  int len = message.length() / 2;
  char[] chars = message.toCharArray();
  String[] hexStr = new String[len];
  byte[] bytes = new byte[len];
  for (int i = 0, j = 0; j < len; i += 2, j++) {
   hexStr[j] = "" + chars[i] + chars[i + 1];
   bytes[j] = (byte) Integer.parseInt(hexStr[j], 16);
  }
  return bytes;
 } 

大概整体就是如上的步骤,但是也是要具体根据厂家的协议来实现通信的过程。

就拿一个我们项目中的demo说一下。
一个蓝牙ble的血压计。 上位机---手机  下位机 -- 血压计
1.血压计与手机连接蓝牙之后。
2.上位机主动向下位机发送一个身份验证指令,下位机收到指令后开始给上位做应答,
3.应答成功,下位机会将测量的血压数据传送到上位机。
4.最后断开连接。

希望本文对大家学习Android蓝牙技术有所帮助。

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索android
蓝牙4.0
android蓝牙4.0开发、android 蓝牙4.0、android蓝牙4.0通信、android 蓝牙4.0 demo、android蓝牙4.0开发坑,以便于您获取更多的相关知识。

时间: 2024-08-22 14:15:03

分享Android 蓝牙4.0(ble)开发的解决方案_Android的相关文章

分享Android 蓝牙4.0(ble)开发的解决方案

最近,随着智能穿戴式设备.智能医疗以及智能家居的普及,蓝牙开发在移动开中显得非常的重要.由于公司需要,研究了一下,蓝牙4.0在Android中的应用. 以下是我的一些总结. 1.先介绍一下关于蓝牙4.0中的一些名词吧:    (1).GATT(Gneric Attibute  Profile) 通过ble连接,读写属性类小数据Profile通用的规范.现在所有的ble应用Profile  都是基于GATT (2).ATT(Attribute Protocal) GATT是基于ATT Potoca

3 0-关于Android手机与CC2540的通讯问题(关键字:BLE,android 蓝牙3.0)

问题描述 关于Android手机与CC2540的通讯问题(关键字:BLE,android 蓝牙3.0) Android程序想与CC2540通讯,用的是蓝牙3.0 Android程序发送一段命令,然后CC2540收到了命令后再反馈一段不同的命令,android如何收到这个命令呢? 目前我仅仅知道用不同的UUID去得到不同的服务,这些服务中的属性有的可以读,有的可以写,但是这些东西都不是我想到的那个反馈命令,我获取了全部的属性,一个个地读,读出来没有我想要的. 跪求!!!!!!!!!!!!!!!如何

蓝牙4 0 蓝牙ble 通讯-android蓝牙4.0(BLE)数据通讯

问题描述 android蓝牙4.0(BLE)数据通讯 https://developer.android.com/samples/BluetoothLeGatt/src/com.example.android.bluetoothlegatt/BluetoothLeService.html 这里面是android官网的demo,但是里面貌似没有数据发送和接收的部分,请好心人告诉我下怎么做数据通讯,或者有谁给提供下有用的资料也行,谢谢哈! 解决方案 Demo中有数据发送和接收,仔细看看吧. 解决方案

Android 蓝牙2.0的使用方法详解_Android

本文为大家分享了Android操作蓝牙2.0的使用方法,供大家参考,具体内容如下 1.Android操作蓝牙2.0的使用流程 (1)找到设备uuid (2)获取蓝牙适配器,使得蓝牙处于可发现模式,获取下位机的socket,并且与上位机建立建立连接,获取获取输入流和输出流,两个流都不为空时,表示连接成功.否则是连接失败. (3).与下位机的socket开始通信. (4).通信结束后,断开连接(关闭流,关闭socket) 2接下来接直接上代码:2.1找到设备uuid(一般厂商都会给开发者提供) 复制

Android 蓝牙2.0的使用方法详解

本文为大家分享了Android操作蓝牙2.0的使用方法,供大家参考,具体内容如下 1.Android操作蓝牙2.0的使用流程 (1)找到设备uuid (2)获取蓝牙适配器,使得蓝牙处于可发现模式,获取下位机的socket,并且与上位机建立建立连接,获取获取输入流和输出流,两个流都不为空时,表示连接成功.否则是连接失败. (3).与下位机的socket开始通信. (4).通信结束后,断开连接(关闭流,关闭socket) 2接下来接直接上代码: 2.1找到设备uuid(一般厂商都会给开发者提供) 复

如何搜索蓝牙4.0 BLE 设备?

问题描述 如何搜索蓝牙4.0 BLE 设备? 求代码如何搜索蓝牙设备,此设备使用蓝牙4.0技术!搜索了很多例子,但许多例子只能搜索到手机蓝牙设备,希望好心人帮帮忙. 解决方案 android搜索蓝牙时,区分所搜索到的设备是2.0还是BLE蓝牙4.0 BLE

针对蓝牙4.0 BLE通讯过程的逆向和攻击

本文讲的是针对蓝牙4.0 BLE通讯过程的逆向和攻击,从6个月前,我就开始针对BLE设备进行学习和研究,其中接触到了一些关于BLE逆向的博客和文章,但是相关内容都没有给出很好的方案.因此通过我的这篇文章,你将会很好地了解如何进行BLE 4.0通讯的逆向工程并利用它.  在开始之前,我们首先需要了解蓝牙通信,通常情况下有2种类型的蓝牙通信: 经典蓝牙,即蓝牙2.0 低功耗蓝牙,即BLE 4.0 实际上,经典的蓝牙规范从蓝牙1.0和1.0B开始,这些规范由蓝牙技术联盟(Bluetooth SIG)来

关于android蓝牙4.0通信的问题

问题描述 关于android蓝牙4.0通信的问题 请问一下,有没有谁做过关于android蓝牙4.0编程,搜索BLE设备连接通讯,可以接受短信和邮件的demo.

android 蓝牙-Android蓝牙4.0串口通讯问题

问题描述 Android蓝牙4.0串口通讯问题 大神,我通过UUID特征值去获取设备信息,如设备型号.设备名称.电量.信号.但是怎么也接收不到血糖或者血压值.这是怎么情况?能帮忙分析一下吗? 解决方案 http://blog.csdn.net/innost/article/details/9187199 解决方案二: 血糖或者血压值这类东东,是非标准的,你怎么就能确认可以获取到呢? 备型号.设备名称.电量.信号此类,现在的 BT 协议很多是支持的,但并不代表协议能支持所有你想要的功能与数据. 解