您的位置:首页 > 产品设计 > UI/UE

蓝牙相关知识梳理

2018-04-03 11:37 169 查看
连接流程:
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//蓝牙适配判断开启:
if (!mBluetoothAdapter.isEnabled()) {
// 未启动
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
mActivity.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
// 已启动,搜索
search();
}
//    启动回调
public boolean onActivityResult(int requestCode, int resultCode, Intent data) {

if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_OK) {
//            启动后开启搜索
search();
return true;
}
return false;
}
//    启动回调
public boolean onActivityResult(int requestCode, int resultCode, Intent data) {

if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_OK) {
//            启动后开启搜索
search();
return true;
}
return false;
}


连接部分有三种情况:
1、直接连接已知设备:
BluetoothDevice target = mBluetoothAdapter.getRemoteDevice(RemoteDeviceAddr);
if (target != null) {
bluetoothGatt = target.connectGatt(mActivity, false, bluetoothGattCallback);
// BLUETOOTH_NAME = target.getName();
// aniStart();
}2、选取绑定设备连接:
BluetoothDevice target = null;
Set<BluetoothDevice> bondedDevices = mBluetoothAdapter.getBondedDevices();
for (BluetoothDevice bluetoothDevice : bondedDevices) {
Log.d("tag.name..",bluetoothDevice.getName());
if (BLUETOOTH_NAME.equalsIgnoreCase(bluetoothDevice.getName())) {
target = bluetoothDevice;
break;
}
}3、搜索新设备:
mBluetoothAdapter.startLeScan(mLeScanCallback);private final BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

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

if (BLUETOOTH_NAME.equalsIgnoreCase(device.getName())) {
showDismiss();
isSmart = true;
if (bluetoothGatt != null) {
bluetoothGatt.disconnect();
bluetoothGatt.close();
bluetoothGatt = null;
}
bluetoothGatt = device.connectGatt(mActivity, false, bluetoothGattCallback);
scanLeDevice(false);
}

}
};归根结底就是  BluetoothDevice进行connectGatt操作;

遇到的问题:
1、红米Note4X 连接蓝牙模块失败问题:
可能原因:
应该是Android 6.0使用蓝牙需要定位权限。
A、
BLE 连接时对端一定要处于 Advertising 状态,否则是不可能连接成功的。你的 connect 一定要在BLE onScanResult 中做,确定扫到设备才进行 connect。
B、
每一次连接都会生成一个Gatt对象,每一个Gatt对象都需要断开连接,不然的话,一旦其中有一个Gatt对象没有断开连接,系统就会认为你是在连接的,让你连扫描都扫描不到这个设备,就别说继续连接了

C、
gatt的close和disconnect的区别在于,close除了断开连接外,还会释放掉所有资源,导致不可以直接在后面的操作中用gatt对象的connect直接连接,而disconnect并不释放资源,所以,所有的资源还保存着,就可以用Gatt的connect进行简单恢复连接,而不是在device那一层进行操作。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Bluetooth