1. 使用蓝牙和硬件通信,发送信号;第一次搞,困难多多啊。但是,,,是吧
2. 准备开发蓝牙,就需要Android对动态权限的处理(这里大家自己解决)
3. 保证动态权限OK,往下执行,需要了解一下蓝牙的知识信息(这里大家可以官网google一下,也可以百度野区撩一眼),现在对蓝牙硬件的开发,大多是对BLE4.0以上的处理 (BLE和传统蓝牙技术的区别和优点,自己百度google一下)
4. 蓝牙开发,首先要确保打开蓝牙
5.蓝牙打开后,执行扫描蓝牙;扫描到就可以去连接了
6.蓝牙连接
7. 主要的工具类和连接需要的服务Service
package com.chni.cardiochek.bluetooth;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;
import java.util.List;
@SuppressLint("NewApi")
public class DeviceControlUtils {
private final static String TAG = DeviceControlUtils.class.getSimpleName();
public static DeviceControlUtils mDeviceControlUtils = null;
/**
* 获取DeviceControlUtils单利
* @param mContext
* @return
*/
public static DeviceControlUtils getInstance(Activity mContext){
if(mDeviceControlUtils==null){
mDeviceControlUtils = new DeviceControlUtils(mContext);
}
return mDeviceControlUtils;
}
/**
* 构造函数
* @param mContext
*/
private DeviceControlUtils(Context mContext){
this.mContext = mContext;
}
private BluetoothLeService mBluetoothLeService=null;
private Context mContext = null;
private String mDeviceAddress = null;
private String mDeviceName = null;
private boolean mConnected = false;
/**
* 初始化蓝牙逻辑
* @param deviceAddress
*/
public void init(String deviceAddress){
this.mDeviceAddress = deviceAddress;
//先注册蓝牙服务
Intent gattServiceIntent = new Intent(mContext, BluetoothLeService.class);
boolean bll = mContext.bindService(gattServiceIntent, mServiceConnection,mContext.BIND_AUTO_CREATE);
if (bll) {
System.out.println("---------------");
} else {
System.out.println("===============");
}
//在注册Receiver
mContext.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
if (mBluetoothLeService != null) {
final boolean result = mBluetoothLeService.connect(mDeviceAddress);
Log.d(TAG, "Connect request result=" + result);
}
}
// Code to manage Service lifecycle.
private final ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName,
IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
}
mBluetoothLeService.connect(mDeviceAddress);
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
mConnected = true;
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
mConnected = false;
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
if(mBluetoothLeService!=null)
displayGattServices(mBluetoothLeService.getSupportedGattServices());
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
//获取数据
// displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
}
}
};
/**
* 手动处理连接service
*/
public void connectedService(){
mBluetoothLeService.connect(mDeviceAddress);
}
/**
* 手动断开service连接
*/
public void disconnectService(){
if(mServiceConnection!=null) {
mBluetoothLeService.disconnect();
}
}
/**
* 解绑service
*/
public void onDestroy() {
if(mServiceConnection!=null) {
mContext.unbindService(mServiceConnection);
mBluetoothLeService = null;
}
}
/**
* 解绑Receiver
*/
public void onPause() {
if(mConnected) {
mContext.unregisterReceiver(mGattUpdateReceiver);
mConnected = false;
}
}
/**
* 释放关闭蓝牙服务的部分
*/
public void releaseBluetoothService(){
if(mBluetoothLeService!=null) {
mBluetoothLeService.close();
disconnectService();
onPause();
onDestroy();
}
}
/**
* 展示gattServices里的特征点,过滤UUID执行不同的操作
* @param gattServices
*/
private void displayGattServices(List gattServices) {
if (gattServices == null)
return;
String uuid = null;
for (BluetoothGattService gattService : gattServices) {
uuid = gattService.getUuid().toString();
Log.d(TAG, "displayGattServices: "+uuid);
List gattCharacteristics = gattService.getCharacteristics();
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
uuid = gattCharacteristic.getUuid().toString();
if (uuid.toUpperCase().contains(BluetoothLeService.BLUETOOTH_WHITE_ORDER_TO_LOCK_UUID)) {
//写入数据
writeDataToLock(gattCharacteristic);
}else if (uuid.toUpperCase().contains(BluetoothLeService.BLUETOOTH_LOCK_NOTIFY_READ_UUID)) {
if(mBluetoothLeService!=null)
mBluetoothLeService.setCharacteristicNotification(gattCharacteristic, true);
}
}
}
}
/**
* 写入数据给蓝牙锁 https://blog.csdn.net/java__han/article/details/77848223
* @param gattCharacteristic
*/
public void writeDataToLock(BluetoothGattCharacteristic gattCharacteristic){
byte [] send = new byte[20];
byte[] downOrder = { (byte) 0x95,0x04, 0x20, 0x40, 0x00, 0x01,0x00,0x00};
int crc16Text = CRC16CheckUtil.getCRC16(send,send.length-2);
//String crc16result = String.format("%02x",crc16Text);
send[6]=(byte) Integer.parseInt(Integer.toHexString(crc16Text&0xff), 16);
send[7]=(byte) Integer.parseInt(Integer.toHexString((crc16Text>>8)&0xff), 16);
gattCharacteristic.setValue(send);
boolean status =mBluetoothLeService.writeCharacteristic(gattCharacteristic);
if(status){
}
}
/**
* 过滤ACTION
* @return
*/
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
intentFilter.addAction(BluetoothLeService.EXTRA_DATA);
return intentFilter;
}
}
服务类:(执行连接和写入回调)
/**
* Service for managing connection and data communication with a GATT server
* hosted on a given Bluetooth LE device.
*
* 参考:
* https://github.com/lidong1665/Android-ble 和 demo
* https://blog.csdn.net/qq_32274413/article/details/53289579
*
*/
@SuppressLint("NewApi")
public class BluetoothLeService extends Service {
private final static String TAG = BluetoothLeService.class.getSimpleName();
private BluetoothManager mBluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private String mBluetoothDeviceAddress;
private BluetoothGatt mBluetoothGatt;
public static BluetoothGattCharacteristic characteristic = null;//临时存储写入时的特征值
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;
public final static String ACTION_GATT_CONNECTED = "com.motian.bai.core.ACTION_GATT_CONNECTED";
public final static String ACTION_GATT_DISCONNECTED = "com.motian.bai.core.ACTION_GATT_DISCONNECTED";
public final static String ACTION_GATT_SERVICES_DISCOVERED = "com.motian.bai.core.ACTION_GATT_SERVICES_DISCOVERED";
public final static String ACTION_DATA_AVAILABLE = "com.motian.bai.core.ACTION_DATA_AVAILABLE";
public final static String EXTRA_DATA = "com.motian.bai.core.EXTRA_DATA";
//(官方API文档固定标准)
public static String CLIENT_CHARACTERISTIC_CONFIG = "00001101-0000-1000-8000-00805F9B34FB";
//过滤车位锁写uuid
public static String BLUETOOTH_WHITE_ORDER_TO_LOCK_UUID = "DE940002-F7ED-22A0-9248-782E58730ED4";
//过滤车位锁消息回调,notify的uuid
public static String BLUETOOTH_LOCK_NOTIFY_READ_UUID = "DE940003-F7ED-22A0-9248-782E58730ED4";
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
/**
* 连接状态改变
*/
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String intentAction;
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);
if(status == 0){//值为0:不确定因素导致连接失败。不确定因素可能为信号太弱等
mBluetoothGatt.connect();
}else {//由于协议栈原因导致连接建立失败。所以清除掉连接后重新建立连接
close();//解决133
connect(mBluetoothDeviceAddress);
}
}
}
/**
* 发现服务,在蓝牙连接的时候会调用
*/
@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);
}
}
/**
* 在指定的characteristic特征端口中读取数据
*/
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
Log.d(TAG, "onCharacteristicRead:" +status);
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
/**
* 写入操作的回调结果
*/
@Override
public void onCharacteristicWrite(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
if(status == 0){//写入成功
String value = CRC16CheckUtil.bytesToHexString(characteristic.getValue());
Log.e("open_lock","蓝牙"+value);
disconnect();//成功后,断开服务
close();
}else{
//写入失败,从新写入
mBluetoothGatt.writeCharacteristic(BluetoothLeService.characteristic);
}
}
/**
* when connected successfully will callback this method
* this method can dealwith send password or data analyze
* @param gatt
* @param characteristic
*/
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
@Override
public void onDescriptorWrite(BluetoothGatt gatt,
BluetoothGattDescriptor descriptor, int status) {
String value = CRC16CheckUtil.bytesToHexString(descriptor.getValue());
UUID uuid = descriptor.getCharacteristic().getUuid();
Log.e("onDescriptorWrite",uuid.toString());
}
/**
* 读取蓝牙信号
* @param gatt
* @param rssi
* @param status
*/
@Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
System.out.println("rssi = " + rssi);
}
@Override
public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
super.onReliableWriteCompleted(gatt, status);
}
};
private void broadcastUpdate(final String action) {
final Intent intent = new Intent(action);
sendBroadcast(intent);
}
private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) {
final Intent intent = new Intent(action);
byte[] heartRate = characteristic.getValue();
String s = CRC16CheckUtil.byte2HexStr(heartRate);
String data = CRC16CheckUtil.print10(s);
if (data != null ) {
intent.putExtra(EXTRA_DATA, data);
}
sendBroadcast(intent);
}
public class LocalBinder extends Binder {
public BluetoothLeService getService() {
return BluetoothLeService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
close();
return super.onUnbind(intent);
}
private final IBinder mBinder = new LocalBinder();
/**
* Initializes a reference to the local Bluetooth adapter.
*/
public boolean initialize() {
if (mBluetoothManager == null) {
mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
if (mBluetoothManager == null) {
Log.e(TAG, "Unable to initialize BluetoothManager.");
return false;
}
}
mBluetoothAdapter = mBluetoothManager.getAdapter();
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.
*/
public boolean connect(final String address) {
if (mBluetoothAdapter == null || address == null) {
Log.w(TAG,"BluetoothAdapter not initialized or unspecified address.");
return false;
}
if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null) {
if (mBluetoothGatt.connect()) {
mConnectionState = STATE_CONNECTING;
return true;
} else {
return false;
}
}
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null) {
Log.d(TAG, "没有设备");
return false;
}
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
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;
}
public boolean writeCharacteristic(BluetoothGattCharacteristic characteristic) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return false;
}
this.characteristic = characteristic;
return mBluetoothGatt.writeCharacteristic(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 readCharacteristic(BluetoothGattCharacteristic characteristic) {
Log.d(TAG, "readCharacteristic: "+characteristic.getProperties());
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.d(TAG, "BluetoothAdapter为空");
return;
}
mBluetoothGatt.readCharacteristic(characteristic);
}
/**
* 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.d(TAG, "BluetoothAdapter为空");
return;
}
boolean isEnableNotification = mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID
.fromString(CLIENT_CHARACTERISTIC_CONFIG));
if (isEnableNotification) {
List descriptors = characteristic.getDescriptors();
for (BluetoothGattDescriptor dp : descriptors) {
dp.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
if(mBluetoothGatt!=null)
mBluetoothGatt.writeDescriptor(dp);
}
readCharacteristic(characteristic);
if(mBluetoothGatt!=null)
mBluetoothGatt.readRemoteRssi();
}
if (descriptor != null) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
}
}
/**
* 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 getSupportedGattServices() {
if (mBluetoothGatt == null)
return null;
return mBluetoothGatt.getServices();
}
/**
* Read the RSSI for a connected remote device.
* */
public boolean getRssiVal() {
if (mBluetoothGatt == null)
return false;
return mBluetoothGatt.readRemoteRssi();
}
}
8.重要的编码,给蓝牙硬件写入的16进制编码
参考:
https://blog.csdn.net/java__han/article/details/77848223
public class CRC16CheckUtil {
static final char TABLE[] = { 0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, 0xC601, 0x06C0, 0x0780, 0xC741,
0x0500, 0xC5C1, 0xC481, 0x0440, 0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40, 0x0A00, 0xCAC1, 0xCB81, 0x0B40,
0xC901, 0x09C0, 0x0880, 0xC841, 0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40, 0x1E00, 0xDEC1, 0xDF81, 0x1F40,
0xDD01, 0x1DC0, 0x1C80, 0xDC41, 0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641, 0xD201, 0x12C0, 0x1380, 0xD341,
0x1100, 0xD1C1, 0xD081, 0x1040, 0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240, 0x3600, 0xF6C1, 0xF781, 0x3740,
0xF501, 0x35C0, 0x3480, 0xF441, 0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41, 0xFA01, 0x3AC0, 0x3B80, 0xFB41,
0x3900, 0xF9C1, 0xF881, 0x3840, 0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41, 0xEE01, 0x2EC0, 0x2F80, 0xEF41,
0x2D00, 0xEDC1, 0xEC81, 0x2C40, 0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640, 0x2200, 0xE2C1, 0xE381, 0x2340,
0xE101, 0x21C0, 0x2080, 0xE041, 0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240, 0x6600, 0xA6C1, 0xA781, 0x6740,
0xA501, 0x65C0, 0x6480, 0xA441, 0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41, 0xAA01, 0x6AC0, 0x6B80, 0xAB41,
0x6900, 0xA9C1, 0xA881, 0x6840, 0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41, 0xBE01, 0x7EC0, 0x7F80, 0xBF41,
0x7D00, 0xBDC1, 0xBC81, 0x7C40, 0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640, 0x7200, 0xB2C1, 0xB381, 0x7340,
0xB101, 0x71C0, 0x7080, 0xB041, 0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241, 0x9601, 0x56C0, 0x5780, 0x9741,
0x5500, 0x95C1, 0x9481, 0x5440, 0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40, 0x5A00, 0x9AC1, 0x9B81, 0x5B40,
0x9901, 0x59C0, 0x5880, 0x9841, 0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40, 0x4E00, 0x8EC1, 0x8F81, 0x4F40,
0x8D01, 0x4DC0, 0x4C80, 0x8C41, 0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641, 0x8201, 0x42C0, 0x4380, 0x8341,
0x4100, 0x81C1, 0x8081, 0x4040, };
public static int getCRC16(byte [] data,int length){
int crc_reg = 0xffff;
for (int i = 0; i < length; i++) {
crc_reg = (crc_reg>>8) ^ TABLE[(crc_reg ^ data[i]) & 0xff];
}
return crc_reg;
}
/* *
* Convert byte[] to hex string.这里我们可以将byte转换成int,然后利用Integer.toHexString(int)
*来转换成16进制字符串。
* @param src byte[] data
* @return hex string
*/
public static String bytesToHexString(byte[] src){
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
/**
* 将16进制 转换成10进制
*
* @param str
* @return
*/
public static String print10(String str) {
StringBuffer buff = new StringBuffer();
String array[] = str.split(" ");
for (int i = 0; i < array.length; i++) {
int num = Integer.parseInt(array[i], 16);
buff.append(String.valueOf((char) num));
}
return buff.toString();
}
/**
* byte转16进制
*
* @param b
* @return
*/
public static String byte2HexStr(byte[] b) {
String stmp = "";
StringBuilder sb = new StringBuilder("");
for (int n = 0; n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0xFF);
sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
sb.append(" ");
}
return sb.toString().toUpperCase().trim();
}
}
9. 开发过程中的几个关键点:
一。特征点过滤和处理
二。写入操作编码
三。写入回调部分
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
/**
* 连接状态改变
*/
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String intentAction;
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);
if(status == 0){//值为0:不确定因素导致连接失败。不确定因素可能为信号太弱等
mBluetoothGatt.connect();
}else {//由于协议栈原因导致连接建立失败。所以清除掉连接后重新建立连接
close();//解决133
connect(mBluetoothDeviceAddress);
}
}
}
/**
* 发现服务,在蓝牙连接的时候会调用
*/
@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);
}
}
/**
* 在指定的characteristic特征端口中读取数据
*/
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
Log.d(TAG, "onCharacteristicRead:" +status);
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
/**
* 写入操作的回调结果
*/
@Override
public void onCharacteristicWrite(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
if(status == 0){//写入成功
String value = CRC16CheckUtil.bytesToHexString(characteristic.getValue());
Log.e("open_lock","蓝牙"+value);
disconnect();//成功后,断开服务
close();
}else{
//写入失败,从新写入
mBluetoothGatt.writeCharacteristic(BluetoothLeService.characteristic);
}
}
/**
* when connected successfully will callback this method
* this method can dealwith send password or data analyze
* @param gatt
* @param characteristic
*/
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
@Override
public void onDescriptorWrite(BluetoothGatt gatt,
BluetoothGattDescriptor descriptor, int status) {
String value = CRC16CheckUtil.bytesToHexString(descriptor.getValue());
UUID uuid = descriptor.getCharacteristic().getUuid();
Log.e("onDescriptorWrite",uuid.toString());
}
/**
* 读取蓝牙信号
* @param gatt
* @param rssi
* @param status
*/
@Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
System.out.println("rssi = " + rssi);
}
@Override
public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
super.onReliableWriteCompleted(gatt, status);
}
};
10.这个蓝牙开发需要硬件支持,写入的指令要和硬件交流好;再有就是参考大牛的思路和代码
https://blog.csdn.net/java__han/article/details/77848223 写入编码指令16进制处理
https://github.com/lidong1665/Android-ble 和 demo https://blog.csdn.net/qq_32274413/article/details/53289579 蓝牙开发和服务
11.总结:蓝牙开发花了三天时间完成通信和编码,开始的痛苦和过程的繁琐加上结果的惊喜,还不错的
12.给出demo吧
android bluetooth connect
QQ :1105230742 欢迎交流