欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2024-02-27 19:39:27
最近,随着智能穿戴式设备、智能医疗以及智能家居的普及,蓝牙开发在移动开中显得非常的重要。由于公司需要,研究了一下,蓝牙4.0在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蓝牙技术有所帮助。