
21首先获取BluetoothManager
复制代码 代码如下:
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(ContextBLUETOOTH_SERVICE);
22获取BluetoothAdapter
复制代码 代码如下:
BluetoothAdapter mBluetoothAdapter = bluetoothManagergetAdapter();
23创建BluetoothAdapterLeScanCallback
private BluetoothAdapterLeScanCallback mLeScanCallback = new BluetoothAdapterLeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, final byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
String struuid = NumberUtilsbytes2HexString(NumberUtilsreverseBytes(scanRecord))replace("-", "")toLowerCase();
if (device!=null && struuidcontains(DEVICE_UUID_PREFIXtoLowerCase())) {
mBluetoothDevicesadd(device);
}
} catch (Exception e) {
eprintStackTrace();
}
}
});
}
};
24开始搜索设备。
复制代码 代码如下:
mBluetoothAdapterstartLeScan(mLeScanCallback);
25BluetoothDevice 描述了一个蓝牙设备 提供了getAddress()设备Mac地址,getName()设备的名称。
26开始连接设备
/
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(androidbluetoothBluetoothGatt, int, int)}
callback
/
public boolean connect(final String address) {
if (mBluetoothAdapter == null || address == null) {
Logw(TAG, "BluetoothAdapter not initialized or unspecified address");
return false;
}
// Previously connected device Try to reconnect (先前连接的设备。 尝试重新连接)
if (mBluetoothDeviceAddress != null && addressequals(mBluetoothDeviceAddress) && mBluetoothGatt != null) {
Logd(TAG, "Trying to use an existing mBluetoothGatt for connection");
if (mBluetoothGattconnect()) {
mConnectionState = STATE_CONNECTING;
return true;
} else {
return false;
}
}
final BluetoothDevice device = mBluetoothAdaptergetRemoteDevice(address);
if (device == null) {
Logw(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 = deviceconnectGatt(this, false, mGattCallback);
Logd(TAG, "Trying to create a new connection");
mBluetoothDeviceAddress = address;
mConnectionState = STATE_CONNECTING;
return true;
}
27连接到设备之后获取设备的服务(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 = gattServicegetUuid()toString();
if (uuidcontains("ba11f08c-5f14-0b0d-1080")) {//服务的uuid
//Systemoutprintln("this gattService UUID is:" + gattServicegetUuid()toString());
currentServiceDataput(LIST_NAME, "Service_OX100");
currentServiceDataput(LIST_UUID, uuid);
gattServiceDataadd(currentServiceData);
ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList<>();
List<BluetoothGattCharacteristic> gattCharacteristics = gattServicegetCharacteristics();
ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<>();
// Loops through available Characteristics
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
charasadd(gattCharacteristic);
HashMap<String, String> currentCharaData = new HashMap<>();
uuid = gattCharacteristicgetUuid()toString();
if (uuidtoLowerCase()contains("cd01")) {
currentCharaDataput(LIST_NAME, "cd01");
} else if (uuidtoLowerCase()contains("cd02")) {
currentCharaDataput(LIST_NAME, "cd02");
} else if (uuidtoLowerCase()contains("cd03")) {
currentCharaDataput(LIST_NAME, "cd03");
} else if (uuidtoLowerCase()contains("cd04")) {
currentCharaDataput(LIST_NAME, "cd04");
} else {
currentCharaDataput(LIST_NAME, "write");
}
currentCharaDataput(LIST_UUID, uuid);
gattCharacteristicGroupDataadd(currentCharaData);
}
mGattCharacteristicsadd(charas);
gattCharacteristicDataadd(gattCharacteristicGroupData);
mCharacteristicCD01 = gattServicegetCharacteristic(UUIDfromString("0000cd01-0000-1000-8000-00805f9b34fb"));
mCharacteristicCD02 = gattServicegetCharacteristic(UUIDfromString("0000cd02-0000-1000-8000-00805f9b34fb"));
mCharacteristicCD03 = gattServicegetCharacteristic(UUIDfromString("0000cd03-0000-1000-8000-00805f9b34fb"));
mCharacteristicCD04 = gattServicegetCharacteristic(UUIDfromString("0000cd04-0000-1000-8000-00805f9b34fb"));
mCharacteristicWrite = gattServicegetCharacteristic(UUIDfromString("0000cd20-0000-1000-8000-00805f9b34fb"));
//Systemoutprintln("=======================Set Notification==========================");
// 开始顺序监听,第一个:CD01
mBluetoothLeServicesetCharacteristicNotification(mCharacteristicCD01, true);
mBluetoothLeServicesetCharacteristicNotification(mCharacteristicCD02, true);
mBluetoothLeServicesetCharacteristicNotification(mCharacteristicCD03, true);
mBluetoothLeServicesetCharacteristicNotification(mCharacteristicCD04, true);
}
}
}
28获取到特征之后,找到服务中可以向下位机写指令的特征,向该特征写入指令。
public void wirteCharacteristic(BluetoothGattCharacteristic characteristic) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Logw(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGattwriteCharacteristic(characteristic);
}
29写入成功之后,开始读取设备返回来的数据。
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String intentAction;
//Systemoutprintln("=======status:" + status);
if (newState == BluetoothProfileSTATE_CONNECTED) {
intentAction = ACTION_GATT_CONNECTED;
mConnectionState = STATE_CONNECTED;
broadcastUpdate(intentAction);
Logi(TAG, "Connected to GATT server");
// Attempts to discover services after successful connection
Logi(TAG, "Attempting to start service discovery:" + mBluetoothGattdiscoverServices());
} else if (newState == BluetoothProfileSTATE_DISCONNECTED) {
intentAction = ACTION_GATT_DISCONNECTED;
mConnectionState = STATE_DISCONNECTED;
Logi(TAG, "Disconnected from GATT server");
broadcastUpdate(intentAction);
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGattGATT_SUCCESS) {
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
} else {
Logw(TAG, "onServicesDiscovered received: " + status);
}
}
//从特征中读取数据
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
//Systemoutprintln("onCharacteristicRead");
if (status == BluetoothGattGATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
//向特征中写入数据
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
//Systemoutprintln("--------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 (characteristicgetValue() != null) {
//Systemoutprintln(characteristicgetStringValue(0));
}
//Systemoutprintln("--------onCharacteristicChanged-----");
}
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
//Systemoutprintln("onDescriptorWriteonDescriptorWrite = " + status + ", descriptor =" + descriptorgetUuid()toString());
UUID uuid = descriptorgetCharacteristic()getUuid();
if (uuidequals(UUIDfromString("0000cd01-0000-1000-8000-00805f9b34fb"))) {
broadcastUpdate(ACTION_CD01NOTIDIED);
} else if (uuidequals(UUIDfromString("0000cd02-0000-1000-8000-00805f9b34fb"))) {
broadcastUpdate(ACTION_CD02NOTIDIED);
} else if (uuidequals(UUIDfromString("0000cd03-0000-1000-8000-00805f9b34fb"))) {
broadcastUpdate(ACTION_CD03NOTIDIED);
} else if (uuidequals(UUIDfromString("0000cd04-0000-1000-8000-00805f9b34fb"))) {
broadcastUpdate(ACTION_CD04NOTIDIED);
}
}
@Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
//Systemoutprintln("rssi = " + rssi);
}
};
----------------------------------------------
//从特征中读取数据
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
//Systemoutprintln("onCharacteristicRead");
if (status == BluetoothGattGATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
30、查询蓝牙设备
指令 响应 参数
Param1:蓝牙地址
Param2:设备类 AT+INQ +INQ: <Param1>,<Param2>,<Param3>,
OK
Param3:RSSI 信号强度
举例说明 1:
at+init\r\n ——初始化 SPP库(不能重复初始化) OK
at+iac=9e8b33\r\n——查询任意访问码的蓝牙设备 OK
at+class=0\r\n ——查询各种蓝牙设备类
at+inqm=1,9,48\r\n——查询模式:带 RSSI信号强度指示,超过 9个蓝牙设备响应则终止查询,设定超 时
为 48x128=6144秒。
At+inq\r\n ——查询周边蓝牙设备
+INQ:2:72:D2224,3E0104,FFBC
+INQ:1234:56:0,1F1F,FFC1
+INQ:1234:56:0,1F1F,FFC0
+INQ:1234:56:0,1F1F,FFC1
+INQ:2:72:D2224,3F0104,FFAD
+INQ:1234:56:0,1F1F,FFBE
+INQ:1234:56:0,1F1F,FFC2
+INQ:1234:56:0,1F1F,FFBE
+INQ:2:72:D2224,3F0104,FFBC OK
以上就是关于android蓝牙ble4.0开发共享失败怎么办全部的内容,包括:android蓝牙ble4.0开发共享失败怎么办、android 蓝牙信号强度值怎么转换成距离、等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)