Android 低功耗蓝牙开发与遇到的坑

本文详细介绍了Android低功耗蓝牙的开发流程,包括搜索、连接和通信。在搜索阶段,结合经典蓝牙和低功耗蓝牙进行设备查找,并通过注册回调监听设备发现。特别提醒,缺少Location权限可能造成搜索失败。在连接步骤中,重点讨论了相关代码实现。
摘要由CSDN通过智能技术生成

过程 搜索-配对-连接-通信

目前配对的环节可以省略了

1.搜索:我是传统的蓝牙搜索➕低功耗蓝牙搜索一起使用的

经典蓝牙:调用

mBluetoothAdapter.startDiscovery();

这时我们需要注册一个通知来监听回调

完整代码如下:

/**
 * 普通设备搜索
 */
public void searchDevices() {
    try {
        checkNotNull(mOnSearchDeviceListener);
        if (mBondedList == null) mBondedList = new ArrayList<>();
        if (mNewList == null) mNewList = new ArrayList<>();
        if (mBluetoothAdapter == null) {
            mOnSearchDeviceListener.onError(new NullPointerException(Constants.DEVICE_HAS_NOT_BLUETOOTH_MODULE));
            return;
        }
        if (mReceiver == null) mReceiver = new Receiver();
        // ACTION_FOUND
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        context.registerReceiver(mReceiver, filter);
        // ACTION_DISCOVERY_FINISHED
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        context.registerReceiver(mReceiver, filter);
        mNeedunRegister = true;
        mBondedList.clear();
        mNewList.clear();
        if (mBluetoothAdapter.isDiscovering())
            mBluetoothAdapter.cancelDiscovery();
        mBluetoothAdapter.startDiscovery();
        mOnSearchDeviceListener.onStartDiscovery();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
/**
 * 搜索蓝牙广播
 */
private class Receiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            String action = intent.getAction();
            if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                if (mOnSearchDeviceListener != null)
                    mOnSearchDeviceListener.onStartDiscovery();
            } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() == BluetoothDevice.BOND_NONE) {
                    if (paar != null && !paar.containsKey(device.getAddress())) {
                        paar.put(device.ge
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值