近期完成一个与蓝牙相关的项目,特此总结一下与蓝牙模块的交互。
首先,是蓝牙相干操作的服务,包括,初始化、单例模式、蓝牙开关状态的监听广播、蓝牙的扫描、连接、读取信息、写入命令(Uart串口透传)、等,
public class BluetoothService extends Service implements BluetoothListener, Constants {
private static final String TAG = BluetoothService.class.getName();
private String serviceUUID = "6e400001-b5a3-f393-e0a9-e50e24dcca9e";
//Notify Char UUID
private String notifyCharacteristicUUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e";
//Write Char UUID
private String writeCharacteristicUUID = "6e400002-b5a3-f393-e0a9-e50e24dcca9e";
// private String DESCRIPTOR_CLIENT_CHARACTERISTIC_CONFIGURATION = "00002902-0000-1000-8000-00805f9b34fb";
//READ Char UUID
private final static String READ_CHAR_UUID = "0000ffd2-0000-1000-8000-00805f9b34fb";
private BluetoothManager bluetoothManager;
private BluetoothAdapter bluetoothAdapter;
private BluetoothGatt bluetoothGatt;
private HashMap<String,BluetoothGatt> bluetoothGattHashMap;
private HashMap<String,BluetoothGattCallback> bluetoothGattCallbackHashMap;
private List<BluetoothDevice> scanLeDeviceList = new ArrayList<>();
private boolean isScanning;
private boolean isConnect;
private String bluetoothDeviceAddress;
private int connState = STATE_DISCONNECTED;
// 扫描设备周期,默认10秒暂停扫描
private static final long SCAN_PERIOD = 10 * 1000;
private OnBltScanListener onBltScanListener;
private OnConnStateChangeListener onConnStateChangeListener;
private OnDiscoveredServicesListener onDiscoveredServicesListener;
private OnDataCommunicationListener onDataCommunicationListener;
private OnReadRemoteRssiListener onReadRemoteRssiListener;
private OnOpenBltStateChangeListener onOpenBltStateChangeListener;
private final IBinder iBinder = new LocalBinder();
private static BluetoothService instance = null;
private boolean isSetNotifySuccess = false;
public BluetoothService() {
instance = this;
Log.d(TAG, "BluetoothService initialized.");
bluetoothGattHashMap=new HashMap<>();
bluetoothGattCallbackHashMap=new HashMap<>();
}
public static BluetoothService getInstance() {
if (instance == null) throw new NullPointerException("BluetoothService is not bind.");
return instance;
}
@Override
public IBinder onBind(Intent intent) {
return iBinder;
}
@Override
public boolean onUnbind(Intent intent) {
close();
instance = null;
unRegisterBluetoothStateReceiver();
Log.e(TAG, "onUnbind-------------");
return super.onUnbind(intent);
}
public class LocalBinder extends Binder {
public BluetoothService getService() {
return BluetoothService.this;
}
}
/**
* 设备是否支持蓝牙
*
* @return
*/
public boolean isHasBlt() {
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
}
/**
* 初始化
*
* @return
*/
public boolean initBluetooth() {
if (bluetoothManager == null) {
bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
if (bluetoothManager == null) {
Log.e(TAG, "Unable to initialize BluetoothManager.");
return false;
}
}
bluetoothAdapter = bluetoothManager.getAdapter();
if (bluetoothAdapter == null) {
Log.e(TAG, "Unable to initialize BluetoothAdapter.");
return false;
}
registerBluetoothStateReceiver();
return true;
}
/**
* 蓝牙开/关
*
* @param enable
* @return
*/
public boolean enableBluetooth(boolean enable) {
if (enable) {
if (!bluetoothAdapter.isEnabled()) {
if (bluetoothAdapter.enable()) {
return true;
} else {
return false;
}
}
return true;
} else {
if (bluetoothAdapter.isEnabled()) {
if (bluetoothAdapter.disable()) {
return true;
} else {
return false;
}
}
return true;
}
}
/**
* 注册蓝牙开启状态变更通知
*/
private void registerBluetoothStateReceiver() {
IntentFilter intent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(receiver, intent);
}
/**
* 取消注册蓝牙开启状态变更通知
*/
public void unRegisterBluetoothStateReceiver() {
if (receiver != null) {
try {
unregisterReceiver(receiver);
receiver = null;
} catch (Exception e) {
}
}
}
public void resetListener() {
onDiscoveredServicesListener = null;
onConnStateChangeListener = null;
onDataCommunicationListener = null;
}
/**
* 是否已经开启蓝牙
*
* @return
*/
public boolean isEnableBluetooth() {
return bluetoothAdapter.isEnabled();
}
/**
* 扫描蓝牙设备
*
* @param enable
* @param scanPeriod
*/
public void scanBltDevice(final boolean enable, long scanPeriod) {
if (enable) {
if (isScanning) return;
Log.e(TAG, "scanBltDevice....");
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
isScanning = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (bluetoothAdapter.getBluetoothLeScanner() != null) {
bluetoothAdapter.getBluetoothLeScanner().stopScan(mScanCallback);
} else {
Log.e(TAG, "Please open Bluetooth first");
}
} else {
bluetoothAdapter.stopLeScan(mLeScanCallback);
}
scanLeDeviceList.clear();
if (onBltScanListener != null) {
onBltScanListener.onEndScan();
}
}
}, scanPeriod);
scanLeDeviceList.clear();
isScanning = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (bluetoothAdapter.getBluetoothLeScanner() != null) {
// // 搜索特定服务的蓝牙
// List<ScanFilter> filters = new ArrayList<>();
// ScanFilter filter = new ScanFilter.Builder()
// .setServiceUuid(ParcelUuid.fromString(serviceUUID))
// .build();
// filters.add(filter);
// bluetoothAdapter.getBluetoothLeScanner().startScan(filters, new ScanSettings.Builder()
// .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(), mScanCallback);
// 搜索所有蓝牙设备
bluetoothAdapter.getBluetoothLeScanner().startScan(mScanCallback);
} else {
Log.e(TAG, "Please open Bluetooth first");
}
} else {
bluetoothAdapter.startLeScan(mLeScanCallback);
}
} else {
isScanning = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (bluetoothAdapter.getBluetoothLeScanner() != null) {
bluetoothAdapter.getBluetoothLeScanner().stopScan(mScanCallback);
} else {
Log.e(TAG, "Please open Bluetooth first");
}
} else {
bluetoothAdapter.stopLeScan(mLeScanCallback);
}
scanLeDeviceList.clear();
}
}
/**
* 开始扫描
*
* @param enable
*/
public void scanBltDevice(boolean enable) {
this.scanBltDevice(enable, SCAN_PERIOD);
}
/**
* 是否正在扫描
*
* @return
*/
public boolean isScanning() {
return isScanning;
}
/**
* 连接某个设备
*
* @param address
* @return
*/
public boolean connectBlt(final String address) {
if (isScanning) scanBltDevice(false);
close();
initBluetooth();
if (bluetoothAdapter == null || StringUtil.isEmpty(address)) {
Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
return false;
}
try {
// // 连接的设备已经存在,直接重新连接
// if (bluetoothGattHashMap.get(address) != null) {
// Log.d(TAG, "Trying to use an existing bluetoothGatt for connection.");
// if (bluetoothGattHashMap.get(address).connect()) {
// connState = STATE_CONNECTING;
// return true;
// } else {
// return false;
// }
// }
final BluetoothDevice device = bluetoothAdapter.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.
bluetoothGatt = device.connectGatt(this, false, mGattCallback);
bluetoothGattHashMap.put(address,bluetoothGatt);
Log.d(TAG, "Trying to create a new connection.");
bluetoothDeviceAddress = address;
connState = STATE_CONNECTING;
return true;
} catch (Exception e) {
return false;
}
}
/**
* 清除连接
*/
public void disconnect() {
if (bluetoothAdapter == null || bluetoothGatt == null) {
Log.e(TAG, "BluetoothAdapter not initialized.");
return;
}
bluetoothGatt.disconnect();
}
/**
* 关闭释放资源
*/
public void close() {
isConnect = false;
if (bluetoothGatt == null) {
return;
}
bluetoothGatt.close();
bluetoothGatt = null;
}
/**
* 设备是否已经连接
*
* @return
*/
public boolean isConnect() {
return isConnect;
}
/**
* 获取已连接的设备
*
* @return
*/
public HashMap<String,BluetoothGatt> getBluetoothGattHashMap() {
return bluetoothGattHashMap;
}
/**
* 获取已连接的设备
*
* @return
*/
public BluetoothDevice getConnectedDevice(String mac) {
if (bluetoothGattHashMap.get(mac) == null) return null;
return bluetoothGattHashMap.get(mac).getDevice();
}
public BluetoothGatt getBluetoothGatt() {
return bluetoothGatt;
}
/**
* 获取BluetoothGattService
*
* @return
*/
public List<BluetoothGattService> getSupportedGattServices() {
if (bluetoothGatt == null) return null;
return bluetoothGatt.getServices();
}
/**
* 获取已连接的设备列表
*
* @return
*/
public List<BluetoothDevice> getConnectedDevices() {
if (bluetoothManager == null) return null;
return bluetoothManager.getConnectedDevices(BluetoothProfile.GATT);
}
/**
* 远程设备特征
*
* @param serviceUUID 远程设备服务UUID
* @param characteristicUUID 远程设备特征UUID
*/
public boolean readCharacteristic(String serviceUUID, String characteristicUUID) {
if (bluetoothGatt != null) {
BluetoothGattService service =
bluetoothGatt.getService(UUID.fromString(serviceUUID));
if (service == null) {
return false;
}
BluetoothGattCharacteristic characteristic =
service.getCharacteristic(UUID.fromString(characteristicUUID));
return bluetoothGatt.readCharacteristic(characteristic);
}
return false;
}
/**
* 数据通信(默认服务,默认特征值)
*
* @param data
* @return
*/
public boolean transmit(byte[] data) {
if (data == null) return false;
try {
BluetoothGattService sendService = bluetoothGatt.getService(UUID.fromString(serviceUUID));
if (sendService == null) return false;
BluetoothGattCharacteristic sendGatt = sendService.getCharacteristic(UUID.fromString(writeCharacteristicUUID));
if (sendGatt == null) return false;
sendGatt.setValue(data);
return bluetoothGatt.writeCharacteristic(sendGatt);
} catch (NullPointerException e) {
return false;
}
}
/**
* 向远程设备发送设备特征值
*
* @param serviceUUID
* @param characteristicUUID
* @param value
*/
public boolean writeCharacteristic(String serviceUUID, String characteristicUUID, String value) {
if (bluetoothGatt != null) {
BluetoothGattService service =
bluetoothGatt.getService(UUID.fromString(serviceUUID));
if (service == null) {
return false;
}
BluetoothGattCharacteristic characteristic =
service.getCharacteristic(UUID.fromString(characteristicUUID));
if (characteristic == null) {
return false;
}
characteristic.setValue(value);
return bluetoothGatt.writeCharacteristic(characteristic);
}
return false;
}
/**
* 向远程设备发送设备特征值
*
* @param serviceUUID
* @param characteristicUUID
* @param value
* @return
*/
public boolean writeCharacteristic(String serviceUUID, String characteristicUUID, byte[] value,String mac) {
if (bluetoothGattHashMap.get(mac) != null) {
BluetoothGattService service =
bluetoothGattHashMap.get(mac).getService(UUID.fromString(serviceUUID));
if (service == null) {
return false;
}
BluetoothGattCharacteristic characteristic =
service.getCharacteristic(UUID.fromString(characteristicUUID));
if (characteristic == null) {
return false;
}
characteristic.setValue(value);
Log.e(TAG, "writeCharacteristic 5555");
return bluetoothGattHashMap.get(mac).writeCharacteristic(characteristic);
}
return false;
}
/**
* 读取远程设备给定描述符的值
*
* @return
*/
public boolean readDescriptor(BluetoothGattDescriptor descriptor) {
if (bluetoothGatt == null || descriptor == null) {
Log.w(TAG, "BluetoothGatt is null");
return false;
}
return bluetoothGatt.readDescriptor(descriptor);
}
/**
* 读取远程设备给定描述符的值
*
* @param serviceUUID
* @param characteristicUUID
* @param descriptorUUID
* @return
*/
public boolean readDescriptor(String serviceUUID, String characteristicUUID, String descriptorUUID) {
if (bluetoothGatt == null) {
Log.w(TAG, "BluetoothGatt is null");
return false;
}
BluetoothGattService service =
bluetoothGatt.getService(UUID.fromString(serviceUUID));
if (service == null) {
return false;
}
BluetoothGattCharacteristic characteristic =
service.getCharacteristic(UUID.fromString(characteristicUUID));
if (characteristic == null) {
return false;
}
BluetoothGattDescriptor descriptor =
characteristic.getDescriptor(UUID.fromString(descriptorUUID));
if (descriptor != null) {
return false;
}
return bluetoothGatt.readDescriptor(descriptor);
}
/**
* 读取远程设备RSSI
*
* @return
*/
public boolean readRemoteRssi() {
if (bluetoothGatt == null) return false;
return bluetoothGatt.readRemoteRssi();
}
/**
* 启用或禁用对给定特征的通知
*
* @param characteristic
* @param enabled
*/
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) {
if (bluetoothAdapter == null || bluetoothGatt == null || characteristic == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
Log.e(TAG, "setCharacteristicNotification----------------");
bluetoothGatt.setCharacteristicNotification(characteristic, enabled);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString(notifyCharacteristicUUID));
if (descriptor != null) {
descriptor.setValue(enabled ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE :
BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
boolean isSuccess = bluetoothGatt.writeDescriptor(descriptor);
isSetNotifySuccess = isSuccess;
Log.e(TAG, "setCharacteristicNotification isSuccess" + isSuccess + "characteristic" + characteristic.getUuid().toString());
}
}
/**
* 启用或禁用对给定特征的通知
*
* @param characteristic
* @param enabled
*/
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled,String address) {
if (bluetoothAdapter == null || bluetoothGattHashMap.get(address) == null || characteristic == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
Log.e(TAG, "setCharacteristicNotification----------------");
bluetoothGattHashMap.get(address).setCharacteristicNotification(characteristic, enabled);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString(notifyCharacteristicUUID));
if (descriptor != null) {
descriptor.setValue(enabled ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE :
BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
boolean isSuccess = bluetoothGattHashMap.get(address).writeDescriptor(descriptor);
isSetNotifySuccess = isSuccess;
Log.e(TAG, "setCharacteristicNotification isSuccess" + isSuccess + "characteristic" + characteristic.getUuid().toString());
}
}
public void setCharacteristicNotification(String serviceUUID, String characteristicUUID, boolean enabled,String address) {
if (bluetoothAdapter == null || bluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
BluetoothGattService service =
bluetoothGatt.getService(UUID.fromString(serviceUUID));
BluetoothGattCharacteristic characteristic =
service.getCharacteristic(UUID.fromString(characteristicUUID));
bluetoothGatt.setCharacteristicNotification(characteristic, enabled);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
// descriptor.setValue(enabled ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE :
// BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
boolean resstate = bluetoothGatt.writeDescriptor(descriptor);
Log.e("开启通知的结果状态",""+resstate);
}
/**
* Enable TXNotification
*
* @return
*/
public boolean enableTXNotification()
{
if (bluetoothGatt == null) {
// connect(macAddress);
// showMessage("mBluetoothGatt null" + bluetoothGatt);
// broadcastUpdate(bluetoothGatt,DEVICE_DOES_NOT_SUPPORT_UART);
return false;
}
BluetoothGattService RxService = bluetoothGatt.getService(UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e"));
if (RxService == null) {
// showMessage("Rx service not found!");
// broadcastUpdate(bluetoothGatt,DEVICE_DOES_NOT_SUPPORT_UART);
return false;
}
BluetoothGattCharacteristic TxChar = RxService.getCharacteristic(UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e"));
if (TxChar == null) {
// showMessage("Tx charateristic not found!");
// broadcastUpdate(bluetoothGatt,DEVICE_DOES_NOT_SUPPORT_UART);
return false;
}
bluetoothGatt.setCharacteristicNotification(TxChar,true);
BluetoothGattDescriptor descriptor = TxChar.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
boolean resstate = bluetoothGatt.writeDescriptor(descriptor);
Log.e("开启通知的结果状态",""+resstate);
return true;
}
/**
* 蓝牙开启状态变更广播
*/
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (onOpenBltStateChangeListener != null) {
onOpenBltStateChangeListener.onOpenBltStateChange(state);
}
}
}
};
/**
* 扫描回调
*/
private ScanCallback mScanCallback;
private BluetoothAdapter.LeScanCallback mLeScanCallback;
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (scanLeDeviceList.contains(result.getDevice())) return;
scanLeDeviceList.add(result.getDevice());
if (onBltScanListener != null) {
onBltScanListener.onBltScan(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes());
}
Log.i(TAG, "onScanResult: name: " + result.getDevice().getName() +
", address: " + result.getDevice().getAddress() +
", rssi: " + result.getRssi() + ", scanRecord: " + result.getScanRecord());
}
}
};
} else {
mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
Log.i(TAG, "device name: " + device.getName() + ", address: " + device.getAddress());
if (device == null || scanLeDeviceList.contains(device)) return;
scanLeDeviceList.add(device);
if (onBltScanListener != null) {
onBltScanListener.onBltScan(device, rssi, scanRecord);
}
}
};
}
}
/**
* BluetoothGattCallback
*/
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (onConnStateChangeListener != null) {
onConnStateChangeListener.onConnStateChange(gatt, status, newState);
}
String address = gatt.getDevice().getAddress();
if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.i(TAG, "onConnectionStateChange: DISCONNECTED: " + getConnectedDevices().size());
isConnect = false;
connState = STATE_DISCONNECTED;
Log.i(TAG, "Disconnected from GATT server.");
// close();
} else if (newState == BluetoothProfile.STATE_CONNECTING) {
Log.i(TAG, "onConnectionStateChange: CONNECTING: " + getConnectedDevices().size());
isConnect = false;
connState = STATE_CONNECTING;
Log.i(TAG, "Connecting to GATT server.");
} else if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.i(TAG, "onConnectionStateChange: CONNECTED: " + getConnectedDevices().size());
isConnect = true;
connState = STATE_CONNECTED;
isSetNotifySuccess = false;
Log.i(TAG, "Connected to GATT server.");
// Attempts to discover services after successful cconnectGattonnection.
// Log.i(TAG, "Attempting to start service discovery:" +
// bluetoothGatt.discoverServices());
} else if (newState == BluetoothProfile.STATE_DISCONNECTING) {
Log.i(TAG, "onConnectionStateChange: DISCONNECTING: " + getConnectedDevices().size());
isConnect = false;
connState = STATE_DISCONNECTING;
Log.i(TAG, "Disconnecting from GATT server.");
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
for (BluetoothGattService bluetoothGattService : gatt.getServices()) {
Log.e(TAG, "getUuid" + bluetoothGattService.getUuid() + "getType" + bluetoothGattService.getType());
}
// displayGattServices();
if (onDiscoveredServicesListener != null) {
onDiscoveredServicesListener.onDiscoveredServices(gatt, status);
}
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if (onDataCommunicationListener != null) {
onDataCommunicationListener.onCharacteristicRead(gatt, characteristic, status);
}
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
String address = gatt.getDevice().getAddress();
for (int i = 0; i < characteristic.getValue().length; i++) {
Log.i(TAG, "address: " + address + ",Write: " + characteristic.getValue()[i]);
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
if (onDataCommunicationListener != null) {
onDataCommunicationListener.onCharacteristicChanged(gatt, characteristic);
}
}
@Override
public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
if (onDataCommunicationListener != null) {
onDataCommunicationListener.onDescriptorRead(gatt, descriptor, status);
}
}
@Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
if (onReadRemoteRssiListener != null) {
onReadRemoteRssiListener.onReadRemoteRssi(gatt, rssi, status);
}
}
@Override
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
}
};
/**
* 连接的ble设备所提供的服务
*/
private void displayGattServices() {
Log.e(TAG, "displayGattServices-------------");
if (bluetoothGatt == null) return;
Log.e(TAG, "dibluetoothGatt != null");
BluetoothGattService gattService = bluetoothGatt.getService(UUID.fromString(serviceUUID));
if (gattService == null) return;
Log.e(TAG, "gattService != null");
BluetoothGattCharacteristic mGattCharacteristic = gattService.getCharacteristic(UUID.fromString(writeCharacteristicUUID));
setCharacteristicNotification(mGattCharacteristic, true);
Log.e(TAG, "displayGattServices-----22222--------");
BluetoothGattCharacteristic mNotifyCharacteristic = gattService.getCharacteristic(UUID.fromString(notifyCharacteristicUUID));
setCharacteristicNotification(mNotifyCharacteristic, true);
Log.e(TAG, "displayGattServices-----333333--------");
}
/**
* 连接的ble设备所提供的服务
*/
public void setGattServices(String address) {
Log.e(TAG, "displayGattServices-------------");
if (bluetoothGattHashMap.get(address) == null) return;
Log.e(TAG, "dibluetoothGatt != null");
BluetoothGattService gattService = bluetoothGattHashMap.get(address).getService(UUID.fromString(serviceUUID));
if (gattService == null) return;
Log.e(TAG, "gattService != null");
BluetoothGattCharacteristic mGattCharacteristic = gattService.getCharacteristic(UUID.fromString(writeCharacteristicUUID));
setCharacteristicNotification(mGattCharacteristic, true,address);
Log.e(TAG, "displayGattServices-----22222--------");
BluetoothGattCharacteristic mNotifyCharacteristic = gattService.getCharacteristic(UUID.fromString(notifyCharacteristicUUID));
setCharacteristicNotification(mNotifyCharacteristic, true,address);
Log.e(TAG, "displayGattServices-----333333--------");
}
/**
* 设置开启蓝牙监听
*
* @param onOpenBltStateChangeListener
*/
public void setOnOpenBltStateChangeListener(OnOpenBltStateChangeListener onOpenBltStateChangeListener) {
this.onOpenBltStateChangeListener = onOpenBltStateChangeListener;
}
/**
* 设置扫描设备监听
*
* @param onBltScanListener
*/
public void setOnBltScanListener(OnBltScanListener onBltScanListener) {
this.onBltScanListener = onBltScanListener;
}
/**
* 设置设备连接状态变更监听
*
* @param onConnectListener
*/
public void setOnConnectListener(OnConnStateChangeListener onConnectListener) {
this.onConnStateChangeListener = onConnectListener;
}
/**
* 设置发现设备服务监听
*
* @param onDiscoveredServicesListener
*/
public void setOnDiscoveredServicesListener(OnDiscoveredServicesListener onDiscoveredServicesListener) {
this.onDiscoveredServicesListener = onDiscoveredServicesListener;
}
/**
* 设置数据通信监听
*
* @return
*/
public void setOnDataCommunicationListener(OnDataCommunicationListener onDataCommunicationListener) {
this.onDataCommunicationListener = onDataCommunicationListener;
}
/**
* 设置读取远程Rssi监听
*
* @param onReadRemoteRssiListener
*/
public void setOnReadRemoteRssiListener(OnReadRemoteRssiListener onReadRemoteRssiListener) {
this.onReadRemoteRssiListener = onReadRemoteRssiListener;
}
/**
* 是否开启定位服务
*
* @param context
* @return
*/
public boolean hasLocatioServiceEnable(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
int locationMode = Settings.Secure.LOCATION_MODE_OFF;
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Exception ignored) {
}
if (locationMode != Settings.Secure.LOCATION_MODE_OFF) {
return true;
}
return false;
}
public void setServiceUUID(String serviceUUID) {
this.serviceUUID = serviceUUID;
}
public void setNotifyCharacteristicUUID(String notifyCharacteristicUUID) {
this.notifyCharacteristicUUID = notifyCharacteristicUUID;
}
public void setWriteCharacteristicUUID(String writeCharacteristicUUID) {
this.writeCharacteristicUUID = writeCharacteristicUUID;
}
}
其中
HashMap<String,BluetoothGatt> bluetoothGattHashMap;
HashMap<String,BluetoothGattCallback> bluetoothGattCallbackHashMap;
主要适用于多设备连接,用于保存不同设备的gatt,
使用时,首先进行服务的绑定,然后进行蓝牙设备的初始化即可,另外记得在退出时记得解绑,
使用时的注意点:
1、保证服务存在的情况下,可以多个页面共用一个service,是在不同页面的扫描,连接、数据读取传输等功能,
2、在进行重连操作的时候一定要保证自己的gatt的正确性,比如我每次连接的时候的都是用新的
3、进行读写操作的时候,一定要确保需要进行读写操作的这个服务已经被发现,不然会获取不到数据,及所有的读写操作一定要位于
void onDiscoveredServices(BluetoothGatt gatt, int status);
发现该服务以后。
4、在进行写的操作以前,如果数据回调响应,如果是通过notification,一定要在写入命令之前保证notification状态开启。
5、所有的命令都要放于主线程中进行,如果在子线程中进行可能无法正常发送。(至于为什么,暂时还没有研究清楚,如果以后明白了,再进行补充)。
6、因为蓝牙命令都是串行进行的,如果自己的命令传输有前后顺序的话,可以加入适当的延时操作,来确保设备接收到的命令的顺序是正确的。
因为是初次接触蓝牙模块的开发,许多地方还有很多不足,理解不到的地方也很多,暂时踩过的坑与自己的心得总结暂时就这么多,以后如果有新的心得再进行整理总结。