问答文章1 问答文章501 问答文章1001 问答文章1501 问答文章2001 问答文章2501 问答文章3001 问答文章3501 问答文章4001 问答文章4501 问答文章5001 问答文章5501 问答文章6001 问答文章6501 问答文章7001 问答文章7501 问答文章8001 问答文章8501 问答文章9001 问答文章9501

android蓝牙ble4.0开发共享失败怎么办

发布网友 发布时间:2022-04-21 21:50

我来回答

1个回答

热心网友 时间:2023-07-12 04:13

2.1首先获取BluetoothManager

复制代码 代码如下:
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

2.2获取BluetoothAdapter

复制代码 代码如下:
BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();

2.3创建BluetoothAdapter.LeScanCallback
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

@Override
public void onLeScan(final BluetoothDevice device, int rssi, final byte[] scanRecord) {

runOnUiThread(new Runnable() {
@Override
public void run() {
try {
String struuid = NumberUtils.bytes2HexString(NumberUtils.reverseBytes(scanRecord)).replace("-", "").toLowerCase();
if (device!=null && struuid.contains(DEVICE_UUID_PREFIX.toLowerCase())) {
mBluetoothDevices.add(device);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};

2.4.开始搜索设备。

复制代码 代码如下:
mBluetoothAdapter.startLeScan(mLeScanCallback);

2.5.BluetoothDevice 描述了一个蓝牙设备 提供了getAddress()设备Mac地址,getName()设备的名称。
2.6开始连接设备
/**
* 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;
}

2.7连接到设备之后获取设备的服务(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 = gattService.getUuid().toString();
if (uuid.contains("ba11f08c-5f14-0b0d-1080")) {//服务的uuid
//System.out.println("this gattService UUID is:" + gattService.getUuid().toString());
currentServiceData.put(LIST_NAME, "Service_OX100");
currentServiceData.put(LIST_UUID, uuid);
gattServiceData.add(currentServiceData);
ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList<>();
List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<>();

// Loops through available Characteristics.
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
charas.add(gattCharacteristic);
HashMap<String, String> currentCharaData = new HashMap<>();
uuid = gattCharacteristic.getUuid().toString();
if (uuid.toLowerCase().contains("cd01")) {
currentCharaData.put(LIST_NAME, "cd01");
} else if (uuid.toLowerCase().contains("cd02")) {
currentCharaData.put(LIST_NAME, "cd02");
} else if (uuid.toLowerCase().contains("cd03")) {
currentCharaData.put(LIST_NAME, "cd03");
} else if (uuid.toLowerCase().contains("cd04")) {
currentCharaData.put(LIST_NAME, "cd04");
} else {
currentCharaData.put(LIST_NAME, "write");
}

currentCharaData.put(LIST_UUID, uuid);
gattCharacteristicGroupData.add(currentCharaData);
}

mGattCharacteristics.add(charas);

gattCharacteristicData.add(gattCharacteristicGroupData);

mCharacteristicCD01 = gattService.getCharacteristic(UUID.fromString("0000cd01-0000-1000-8000-00805f9b34fb"));
mCharacteristicCD02 = gattService.getCharacteristic(UUID.fromString("0000cd02-0000-1000-8000-00805f9b34fb"));
mCharacteristicCD03 = gattService.getCharacteristic(UUID.fromString("0000cd03-0000-1000-8000-00805f9b34fb"));
mCharacteristicCD04 = gattService.getCharacteristic(UUID.fromString("0000cd04-0000-1000-8000-00805f9b34fb"));
mCharacteristicWrite = gattService.getCharacteristic(UUID.fromString("0000cd20-0000-1000-8000-00805f9b34fb"));

//System.out.println("=======================Set Notification==========================");
// 开始顺序监听,第一个:CD01
mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD01, true);
mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD02, true);
mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD03, true);
mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD04, true);
}
}
}

2.8获取到特征之后,找到服务中可以向下位机写指令的特征,向该特征写入指令。
public void wirteCharacteristic(BluetoothGattCharacteristic characteristic) {

if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}

mBluetoothGatt.writeCharacteristic(characteristic);

}

2.9写入成功之后,开始读取设备返回来的数据。

private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String intentAction;
//System.out.println("=======status:" + status);
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);
}
}

@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);
}
}
//从特征中读取数据
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
//System.out.println("onCharacteristicRead");
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
//向特征中写入数据
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
//System.out.println("--------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 (characteristic.getValue() != null) {

//System.out.println(characteristic.getStringValue(0));
}
//System.out.println("--------onCharacteristicChanged-----");
}

@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {

//System.out.println("onDescriptorWriteonDescriptorWrite = " + status + ", descriptor =" + descriptor.getUuid().toString());

UUID uuid = descriptor.getCharacteristic().getUuid();
if (uuid.equals(UUID.fromString("0000cd01-0000-1000-8000-00805f9b34fb"))) {
broadcastUpdate(ACTION_CD01NOTIDIED);
} else if (uuid.equals(UUID.fromString("0000cd02-0000-1000-8000-00805f9b34fb"))) {
broadcastUpdate(ACTION_CD02NOTIDIED);
} else if (uuid.equals(UUID.fromString("0000cd03-0000-1000-8000-00805f9b34fb"))) {
broadcastUpdate(ACTION_CD03NOTIDIED);
} else if (uuid.equals(UUID.fromString("0000cd04-0000-1000-8000-00805f9b34fb"))) {
broadcastUpdate(ACTION_CD04NOTIDIED);
}
}

@Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
//System.out.println("rssi = " + rssi);
}
};

----------------------------------------------
//从特征中读取数据
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
//System.out.println("onCharacteristicRead");
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com
苹果手机微信怎么换漂亮字体(苹果手机微信怎么换行输入) 有什么好用的app转换字体 手写转文字的软件 erp可以看评论地址吗 淘宝评论url是什么意思? 揭秘:码牌支付风控升级,背后真相揭秘 电脑电视直播软件哪个好用什么软件好电脑看电视直播 潼南子同街学区是哪些 三极管BU406价格和参数? 火锅料放在冰柜忘了插电一个星期给会坏了吗 火锅的设备有哪些 2000的英语单词怎么写 魔法英语高中短语大全 3dmax快捷键技巧 3D常用快捷键有? 翻译成英文! 不要机译! 新目标初三英语短语 初中英语题,帮帮忙啊! 翻译Connect back through connect back through是什么意思? 华为平板怎么登陆喜马拉雅账号? 华为手机的喜马拉雅小说怎么设置 小米音响怎么绑定喜马拉雅 喜马拉雅不是手机号和邮箱怎么登录 更换手机后再次登录客户端未显示喜马拉雅FM畅听流... 喜马拉雅注册账号几种方法 本人女47岁2018年开始交社保几岁退休 喜马拉雅两个手机同时登录听不同内容 18年中国有多少女生2 我想登录喜马拉雅怎么登陆 现在的女生和十几年前的女生有什么不一样? 英文生字中一的1000个!!超急~` 电话打通了接了来了一句英语第一句发语c 我急需要MAC系统使用说明 智慧的地球的关于智能星球的英文阐述,又名智慧的地球 中文翻译成英文 关于网络的 谢谢!! 辞职书怎么翻译成英语, 谢谢了, 急需下面短文的英文翻译答案,请务必帮忙! 百度知道怎么回事儿? 寻英语高手!!翻译一段文字!!! 智联招聘企业登录,怎么让投递的简历发送到指定邮... 智联招聘的简历怎么发送到企业指定的邮箱? 请问怎么 把简历传到别人的QQ邮箱里 请问大家智联招聘的邮箱怎么注册 智联招聘邮箱地址怎么填 智联招聘上看到公司的邮箱,可以上163直接发邮件到... 怎么在电脑上制作个人简历,并发送到QQ邮箱 最近我的QQ邮箱里收到发件人为智联招聘的邮件,请问... 智联招聘怎么解绑QQ邮箱? 智联招聘怎样阻止面试者把简历发到自己邮箱 企业单位如何修改智联招聘中的邮箱联系方式