前段时间公司一直在做与蓝牙通讯的项目,蓝牙在网络上有很多资料,发现有些地方还是有些讲述不具体的地方,所以决定总结一下。蓝牙低功耗通讯的工具类使用方法。
添加蓝牙权限
<!-- 添加蓝牙权限-->
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
//以下的使用是让其只是在蓝牙低功耗中有效。
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
概念一:因为低功耗蓝牙是从苹果那边继承沿用的,部分硬件上的描述可能会让安卓工程师懵比,苹果在打印特征中只是打印不同的部分,但是安卓确是打印整体。例如苹果中的特征是“FFE1”,在安卓中表示应该是“0000FFE1-0000-1000-8000-00805f9b34fb”。
概念二: 蓝牙通讯之中最重要的就是uuid,因为其他的信息都可以通过扫描之后获得。唯有uuid是需要开发者填写进去的交流的双方约定唯一的“钥匙”。uuid可以理解为端口,基本上分为三种,发送数据的uuid,接收数据的uuid,与功能描述的uuid。在实际的开发中间,有一些蓝牙的厂商,会将发送数据的端口与接收数据的端口使用同一个,那样子就是发送跟接受基本上是同一个uuid,至于功能描述的uuid根据所需的不同的功能加入。而发送数据描述uuid为"00002902-0000-1000-8000-00805f9b34fb"。
开发蓝牙的流程工具类的流程网络上很多教程:
蓝牙初始化——判断蓝牙是否打开(如果没有打开就打开蓝牙)——扫描设备——建立连接——蓝牙通讯
以下贴上蓝牙工具类代码
package Util;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import MyEventBus.QueryInstructionsEventbus;
import de.greenrobot.event.EventBus;
/**
* Created by Administrator on 2017/4/25.
* 低功耗蓝牙的工具类
*/
public class BleUtil {
private static final String TAG = "BleUtil";
private static final long SCAN_PERIOD = 2000;
public static String characterUUID1 = "0000ffe1-0000-1000-8000-00805f9b34fb";//APP发送命令
public static String characterUUID2 = "0000ffe1-0000-1000-8000-00805f9b34fb";//BLE用于回复命令
private static String descriptorUUID = "00002902-0000-1000-8000-00805f9b34fb";//BLE设备特性的UUID
public static byte[] workModel = {0x02, 0x01};
private Context mContext;
private static BleUtil mInstance;
//作为中央来使用和处理数据;
private BluetoothGatt mGatt;
private BluetoothManager manager;
private BTUtilListener mListener;
private BluetoothDevice mCurDevice;
private BluetoothAdapter mBtAdapter;
private List<BluetoothDevice> listDevice;
private List<BluetoothGattService> serviceList;//服务
private List<BluetoothGattCharacteristic> characterList;//特征
private BluetoothGattService service;
public static BluetoothGattCharacteristic character1;
private BluetoothGattCharacteristic character2;
pu