Android BLE (低功耗蓝牙)应用
蓝牙( Bluetooth® ):是一种无线技术标准,可实现固定设备、移动设备和楼宇个人域网之间的短距离数据交换(使用2.4—2.485GHz的ISM波段的UHF无线电波)。蓝牙技术最初由电信巨头爱立信公司于1994年创制,当时是作为RS232数据线的替代方案。蓝牙可连接多个设备,克服了数据同步的难题。
如今蓝牙由蓝牙技术联盟(Bluetooth Special Interest Group,简称SIG)管理。蓝牙技术联盟在全球拥有超过25,000家成员公司,它们分布在电信、计算机、网络、和消费电子等多重领域。IEEE将蓝牙技术列为IEEE 802.15.1,但如今已不再维持该标准。蓝牙技术联盟负责监督蓝牙规范的开发,管理认证项目,并维护商标权益。制造商的设备必须符合蓝牙技术联盟的标准才能以“蓝牙设备”的名义进入市场。蓝牙技术拥有一套专利网络,可发放给符合标准的设备。
一、蓝牙的分类
目前为止蓝牙分为两类:一是经典蓝牙(传统蓝牙),二是低功耗蓝牙(BLE)。顾名思义低功耗蓝牙功耗要比传统蓝牙低,所以广泛使用在智能穿戴设备上。要使安卓设备连接上智能穿戴设备(如智能手表),通过经典蓝牙的socket连接一般是连接不上的(为什么说一般呢,因为有些不良厂家和杂牌智能手环用的不是低功耗蓝牙,这个可以使用经典蓝牙连接上),必须要使用BLE的 GATT连接才能连接上。
二、GATT中的服务、特征值、描述、UUID
GATT连接涉及到四个比较陌生的名词:服务(service)、特征值(Characteristic)、描述(discript)、UUID,下面以智能手环为例分别来解释一下这些名词是什么意思。
- service:服务是包含了若干个数据包(特征值)的集合,一个智能设备可能包含多个服务,使用之恩那个设备生产厂商提供的UUID码来识别。比如之恩那个手环中有测心率的服务、步数的服务,心率和步数的数据包(特征值)都包含在服务中,通过指定的UUID来辨别到底是心率的服务还是步数的服务。
- characteristic:特征值包含在服务里面,顾名思义就是一种数据值,特征值包含一个或者多个描述。如心率是多少,今天走了多少步都可以放进特征值里面,服务中有多个特征值,也是通过UUID来识别
- discript:描述一般是对特征值的值进行描述,比如单位等等的描述,开发中一般用不到(我用不到)
- UUID:由蓝牙设备厂商提供的UUID,UUID是在硬件编程里已经确定了的,想要草所特定的服务、特征值都需要通过UUID来找。
三、安卓中GATT的操作
和经典蓝牙最开始一样,要检测蓝牙是否可用和蓝牙是否打开,这部分代码就不贴出来了。
一般操作GATT的教程都把操作放在安卓的server里面,具体原因还请大神指教。下面的server代码可以直接当作操作GATT的模板来使用,大部分都是些回调函数和对服务、特征值进行操作的方法:
public class UartService extends Service { private final static String TAG = UartService.class.getSimpleName(); List<BluetoothGattService> serviceList = new ArrayList<BluetoothGattService>();//发现的服务列表 private BluetoothAdapter mBluetoothAdapter;//本地蓝牙适配器 private String mBluetoothDeviceAddress;//本地蓝牙MAC地址 private BluetoothGatt mBluetoothGatt;//GTAA /** * 假设生产商提供了一个服务,该服务里面有两个特征值 */ private BluetoothGattService mBluetoothGattService;//gatt服务 private BluetoothGattCharacteristic mBluetoothGattCharacteristic1;//gatt特征值1 private BluetoothGattCharacteristic mBluetoothGattCharacteristic2;//gatt特征值2 private int mConnectionState = STATE_DISCONNECTED; //连接状态常量 private static final int STATE_DISCONNECTED = 0; private static final int STATE_CONNECTING = 1; private static final int STATE_CONNECTED = 2; //蓝牙厂商提供的UUID private static final UUID UUID_SERVICE = UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb"); //服务 private static final UUID UUID_CHARA1 = UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb"); //特征值1 private static final UUID UUID_CHARA2 = UUID.fromString("0000fff4-0000-1000-8000-00805f9b34fb"); //特征值2 // Implements callback methods for GATT events that the app cares about. For example, // connection change and services discovered. private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { if (newState == BluetoothProfile.STATE_CONNECTED) { mConnectionState = STATE_CONNECTED; 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) { mConnectionState = STATE_DISCONNECTED; Log.i(TAG, "Disconnected from GATT server."); } } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) {//服务被发现 if (status == BluetoothGatt.GATT_SUCCESS) { System.out.println("Service has bean discover."); mBluetoothGattService = gatt.getService(UUID_SERVICE);//发现服务 } else { Log.w(TAG, "onServicesDiscovered received: " + status); } } @Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { Utiles.setData(characteristic); } } @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { } @Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { } }; public class LocalBinder extends Binder { UartService getService() { return UartService.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public boolean onUnbind(Intent intent) { // After using a given device, you should make sure that BluetoothGatt.close() is called // such that resources are cleaned up properly. In this particular example, close() is // invoked when the UI is disconnected from the Service. close(); return super.onUnbind(intent); } private final IBinder mBinder = new LocalBinder(); /** * Initializes a reference to the local Bluetooth adapter. * * @return Return true if the initialization is successful. */ public boolean initialize() {//初始化 // For API level 18 and above, get a reference to BluetoothAdapter through // BluetoothManager. mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { Log.e(TAG, "Unable to obtain a BluetoothAdapter."); return false; } return true; } /** * 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; } /** * 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(); } /** * After using a given BLE device, the app must call this method to ensure resources are * released properly. */ public void close() { if (mBluetoothGatt == null) { return; } mBluetoothGatt.close(); mBluetoothGatt = null; } /** * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)} * callback. * * @param characteristic The characteristic to read from. */ public void readCharacteristic(BluetoothGattCharacteristic characteristic) { if (mBluetoothAdapter == null || mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized"); return; } mBluetoothGatt.readCharacteristic(characteristic); } /** * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)} * callback. * * @param characteristic The characteristic to read from. */ public void writeCharacteristic(BluetoothGattCharacteristic characteristic) { if (mBluetoothAdapter == null || mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized"); return; } mBluetoothGatt.writeCharacteristic(characteristic); } public boolean writeCharacteristic1Info(String s){ if(mBluetoothGattService==null){ return false; } mBluetoothGattCharacteristic1 = mBluetoothGattService.getCharacteristic(UUID_CHARA1);//获得特征值1 mBluetoothGattCharacteristic1.setValue(s.getBytes()); writeCharacteristic(mBluetoothGattCharacteristic1); return true; } /** * Enables or disables notification on a give characteristic. * * @param characteristic Characteristic to act on. * @param enabled If true, enable notification. False otherwise. */ public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) { if (mBluetoothAdapter == null || mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized"); return; } mBluetoothGatt.setCharacteristicNotification(characteristic, enabled); } /** * Retrieves a list of supported GATT services on the connected device. This should be * invoked only after {@code BluetoothGatt#discoverServices()} completes successfully. * * @return A {@code List} of supported services. */ public List<BluetoothGattService> getSupportedGattServices() { if (mBluetoothGatt == null) return null; return mBluetoothGatt.getServices(); } @Override//使用startService启动服务时回调 public int onStartCommand(Intent intent, int flags, int startId) { System.out.println("UartService Start"); return super.onStartCommand(intent, flags, startId); } }
ps:在发现服务后,最好把特征值取出来成一个列表,然后使用 setCharacteristicNotification(BluetoothGattCharacteristic characteristic,boolean enabled)方法对所有特征值进行设置,确保服务的特征值都可读可写。
mBluetoothGattService = gatt.getService(UUID_SERVICE);//发现服务 List<BluetoothGattCharacteristic> characteristics = mBluetoothGattService.getCharacteristics(); if(characteristics.size()!=2){return;}//如果此服务不是有2个特征值,说明不是我们要的服务 for (BluetoothGattCharacteristic bluetoothGattCharacteristic : characteristics) { setCharacteristicNotification(bluetoothGattCharacteristic, true); } mBluetoothGattCharacteristic1 = characteristics.get(0); mBluetoothGattCharacteristic2 = characteristics.get(1);
写完Service之后就可以用Service了
四、Service的使用
- 在activity中绑定服务或者开启服务。绑定服务时,当activity销毁时服务跟着销毁;开启服务时,activity销毁,service不会跟着销毁
- 初始化本地蓝牙设备
mUartService.initialize();//初始化本地设备
- 连接
mUartService.connect(String MacAddress);//通过远程设备地址链接到远程设备
- 链接后,回掉service中的onConnectionStateChange方法,其他的回掉方法也是字面意思,非常简单
- 给设备发送数据
writeCharacteristic1Info(String s);
总结
- 要使用service
- 拿到服务之后马上设置特征值为可读可写,否则有可能导致收发数据不正常
- UUID不一定是我的这个,是蓝牙厂商提供的,找硬件编程的小伙伴要UUID
- 有什么问题望各位指教