最近开始接触Android的蓝牙设备问题,严格意义上来说,也算是第二次接触蓝牙机制了,之前对于蓝牙设备的整个过程,也不是太了解,只是接触了一些自己需要的部分。而这次应该算是比较深入的了解了蓝牙机制的部分吧,所以就总结一下这段时间对蓝牙的个人认识吧

(此图片转自http://blog.csdn.net/l331258747/article/details/55261386)

基本上关于蓝牙的流程,这张图片就说明的差不多了,检测用户是否开启了蓝牙——开启蓝牙——扫描蓝牙设备——选择设备连接——发现服务——注册特征码——断开连接,我们就参考这张图,按照响应的顺序来说一下整个蓝牙设备流程的流程方法吧

一:蓝牙检测

我们在启用蓝牙模块的时候,还要先声明一下相关的权限问题

<!-- 步骤(1)设置Google Map API v2 Key,其中com.wei.android.beginning为package的名字 -->
    <permission
        android:name="com.example.administrator.bluetoothdevice.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />
    <uses-permission android:name="com.example.administrator.bluetoothdevice.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="no.nordicsemi.android.LOG" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- 获取位置权限才可以搜索到设备-->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <!-- 蓝牙分享所需的权限 -->
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

蓝牙通信之前,需要先确定设备是否支持蓝牙功能,先初始化一个BluetoothAdapter的实例,

BluetoothAdapter提供了一个静态方法getDefaultAdapter()来获得BluetoothAdapter的实例

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

然后检测蓝牙是否开启并打开蓝牙:

第一种方法:

if(mBluetoothAdapter!=null){

if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

}

第二种方法:

if(mBluetoothAdapter!=null){

if (!mBluetoothAdapter.isEnabled()) {

mBluetoothAdapter.enable();

}

}

而两种方法,都会提示用户开启蓝牙权限。

二:扫描蓝牙设备

在扫描这里,要多添加一个点,就是关于蓝牙连接状态的广播监听,方便在蓝牙是否连接,断开的时候去做相关的逻辑处理,所以还是有必要了解一下的。

if (mCommonBroadcastReceiver != null) {LocalBroadcastManager.getInstance(this).registerReceiver(mCommonBroadcastReceiver, makeIntentFilter());
    //注册蓝牙监听状态改变
    BleProfileServiceReadyActivity.this.registerReceiver(mCommonBroadcastReceiver, makeIntentFilter2());
}
private static IntentFilter makeIntentFilter2() {final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    return intentFilter;
}

注册相关的蓝牙广播监听之后,在监听中做对应的逻辑处理

private BroadcastReceiver mCommonBroadcastReceiver = new BroadcastReceiver() {@Override
    public void onReceive(final Context context, final Intent intent) {final String action = intent.getAction();
        if (BleProfileService.BROADCAST_CONNECTION_STATE.equals(action)) {final int state = intent.getIntExtra(BleProfileService.EXTRA_CONNECTION_STATE,
                    BleProfileService.STATE_DISCONNECTED);
            switch (state) {case BleProfileService.STATE_CONNECTED:break;
                case BleProfileService.STATE_DISCONNECTED:break;

                case BleProfileService.STATE_LINK_LOSS:break;

                case BleProfileService.STATE_CONNECTING:break;
                case BleProfileService.STATE_DISCONNECTING:break;
                default:// there should be no other actions
                    break;
            }}

这里解释一下相关的状态含义:

STATE_DISCONNECTED 状态为断开
STATE_CONNECTING 状态为连接"
STATE_DISCONNECTING 状态为断中
STATE_CONNECTED 状态为连接中

简单的说一下监听方法后,我们在回到主题,关于扫描蓝牙设备的方法:

  1. //搜索附近所有的外围设备
  2. mBluetoothAdapter.startLeScan(mLeScanCallback);
  3. //搜索某些uuid的外围设备。
  4. mBluetoothAdapter.startLeScan(uuid[] ,mLeScanCallback);
  1. 停止扫描
  2. mBluetoothAdapter.stopLeScan(mLeScanCallback);
/*
 * 扫描结果回调
 */
private LeScanCallback mLeScanCallback= new LeScanCallback() {@Override
    public void onLeScan(final BluetoothDevice device, final int rssi,
                         final byte[] scanRecord) {if (mLeScanCallback== null) {return;
        }try {//这里写逻辑代码
        } catch (Exception e) {Log.e("", e.toString());
        }return;
    }
};

解释一下其中的几个参数,当你扫描回调后,基本就可以搜索到周围的蓝牙设备了(前提是蓝牙开启的状态下),在回调的结果中,分别以后三个参数

BluetoothDevice 表示你搜索的设备对象,一般获取设备的mac地址就是从这个对象获取,方法是
getAddress()
rssi 表示的则是设备距离的远近,信号强弱值,有需要这个值可以用数组缓存下来显示
scanRecord 表示的则是蓝牙设备的一些属性值,比如
serviceUUIDs;serviceData;localName等  

在这里要补充说明一点的是,手机扫描设备回调,可能会无法调用,需要手机将位置权限也打开给应用,如果禁掉了应用的位置权限,也会导致扫描设备回调方法无法执行。

三、蓝牙设备连接

关于蓝牙的连接问题,先要说明几个相关类的含义

BluetoothGatt:中央使用和处理数据;
BluetoothGattCallback:中央的回调。

BluetoothGattServer:周边提供数据;

BluetoothGattServerCallback:周边的回调

BluetoothGattService:Gatt服务

BluetoothGattCharacteristic:Gatt特性

BluetoothGattDescriptor:Gatt描述

(转自http://blog.csdn.net/vnanyesheshou/article/details/51943870)

我们要做的连接操作,就是用其中一个对象来处理的:

BluetoothDevicedevice=mBluetoothAdapter.getRemoteDevice(new_mac);

蓝牙设备对象,由BluetoothAdapter根据设备的mac地址来获取

这里需要注意的一个坑是,mac地址必须是FF:FF:FF:FF这样的形式,这点不同于IOS的适配,如果使用其他的设备地址,会出现异常IllegalArgumentException,所以在连接的时候建议处理好此类异常问题:

if (BluetoothManager.BluetoothState()) {try {BluetoothDevice device = getBluetoothAdapter().getRemoteDevice(DeviceAddress);
        Logger.i(TAG, "connectionHandler() " + DeviceAddress);
        if (null != device) {BluetoothGatt gatt = device.connectGatt(getContext(), false, this);
            if (gatt.connect()) {createControl(gatt);
                return true;
            }}} catch (IllegalArgumentException e) {Toast.makeText(getContext(), getContext().getString(R.string.error_device), Toast.LENGTH_SHORT).show();
        return false;
    } catch (Exception e) {Toast.makeText(getContext(), getContext().getString(R.string.error_device), Toast.LENGTH_SHORT).show();
        return false;
    }
}

BluetoothGatt mBluetoothGatt =device.connectGatt(mContext, false,mGattCallback);

这里的三个参数,分别对应的是<1>上下文对象<2>是否自动连接<3>连接回调和连接结果返回。这里重点解释一下第二个参数,个人建议最好是设置为false,如果设置自动连接,则安卓底层会不停的跟对应Mac地址的设备反复连接,连接效率会变得很慢,而且容易发送阻塞,导致后边的设备一直在等前一个设备连接成功的回调,蓝牙设备的连接一定要分开逐个连接,尽量不要形成线程阻碍。

private final BluetoothGattCallback mGattCallbacks = new BluetoothGattCallback() {@Override
    //获取连接状态方法,BLE设备连接上或断开时,会调用到此方
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {if (DEBUG) Log.d(TAG, "onConnectionStateChange");
        if (status == BluetoothGatt.GATT_SUCCESS) {if (newState == BluetoothProfile.STATE_CONNECTED) {showMessage("Bluetooth LE connected");
            }else if (status == BluetoothProfile.STATE_DISCONNECTED) {showMessage("Bluetooth LE disconnected");
            }}}//成功发现设备的services时,调用此方法
    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {if ((status == BluetoothGatt.GATT_SUCCESS) &&(mBluetoothGatt.getService(SERVICE_UUID) != null)) {showMessage("Discover service Successful !!!");
        }}//读写characteristic时会调用到以下方法
    @Override
    public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {if ((status == BluetoothGatt.GATT_SUCCESS) &&(characteristic.getUuid().equals(CHARACTERISTIC_UUID))) {showMessage(characteristic.getStringValue(0));
        }}@Override
    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {BluetoothGattCharacteristic mCharacteristic =getCharacteristic(CHARACTERISTIC_UUID);
        if ((status == BluetoothGatt.GATT_SUCCESS) &&(characteristic.getStringValue(0).equals(mCharacteristic.getStringValue(0)))) {showMessage("CharacteristicWrite Successful !!!");
        }}
};
(代码内容转自http://blog.csdn.net/l331258747/article/details/55261386,也可以参考文章最后留的Demo中的处理方法)
连接是否成功,以及通知的处理,是声明在OnConnectionStateChange,看名字也应该可以看的出来,当设备的蓝牙连接状态发生改变的时候调用的方法。这里也是整个蓝牙最容易出现问题的地方,就是超过了手机连接设备的上限,导致反复连接无法连接上的133状态码问题。(133状态码一般出现在连接设备的数量超过了最大上限值)所以我们要针对这种问题,做相应的处理,尽可能在不使用的蓝牙连接的时候就及时回收掉BlueToothGatt。
     @Override
    publicvoid onConnectionStateChange(BluetoothGatt gatt, intstatus, intnewState) {
        String intentAction;
        if(status == BluetoothGatt.GATT_SUCCESS) {
            if(newState == BluetoothProfile.STATE_CONNECTED) {
                intentAction = BluetoothConstants.ACTION_GATT_CONNECTED;
                mBLEConnectionState = BluetoothConstants.BLE_STATE_CONNECTED;
                broadcastUpdate(intentAction);
                Log.i(TAG, "Connected to GATT server.");
                Log.i(TAG, "Attempting to start service discovery:"  + mBluetoothGatt.discoverServices());
            elseif (newState == BluetoothProfile.STATE_DISCONNECTED) {
                intentAction = BluetoothConstants.ACTION_GATT_DISCONNECTED;
                mBLEConnectionState = BluetoothConstants.BLE_STATE_DISCONNECTED;
                close(); // 防止出现status 133
                Log.i(TAG, "Disconnected from GATT server.");
                broadcastUpdate(intentAction);
            }
        else{
            Log.d(TAG, "onConnectionStateChange received: "  + status);
            intentAction = BluetoothConstants.GATT_STATUS_133;
            mBLEConnectionState = BluetoothConstants.BLE_STATE_DISCONNECTED;
            close(); // 防止出现status 133
            broadcastUpdate(intentAction);
            connect(reConnectAddress);
        }
    }

(转自http://blog.csdn.net/baidu_26352053/article/details/54571688)

四、发现服务,注册特征码

onServiceAdded需要注意我们的特征码一定不能在别的地方注册,因为蓝牙连接是一个耗时操作,如果你提前注册了特征码,很可能注册不成功,一定放在onServiceAdded方法下去注册,否则你会发现根本无法操作蓝牙设备
   private final BluetoothGattServerCallback mCallbacks = new BluetoothGattServerCallback() {@Override
        //获取连接状态方法,BLE设备连接上或断开时,会调用到此方
        public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {if (DEBUG) Log.d(TAG, "onConnectionStateChange: newState=" + newState);
            if (status == BluetoothGatt.GATT_SUCCESS) {if (newState == BluetoothProfile.STATE_CONNECTED) {mDevice = device;
                    String devicename = device.getName();
                    String address = device.getAddress();
                    notifyConnected(devicename);
                    beginNotification();
                } else if (status == BluetoothProfile.STATE_DISCONNECTED) {stopNotification();
                    notifyDisconnected();
                    mDevice = null;
                }}}//service添加成功会调用此方
        @Override
        public void onServiceAdded(int status, BluetoothGattService service) {if (DEBUG) Log.d(TAG, "onServiceAdded()");
            if (status == BluetoothGatt.GATT_SUCCESS) notifyServiceAdded();
        }//读写Characteristic,在此获得客户端发来的消息
        @Override
        public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId,BluetoothGattCharacteristic characteristic,
                                                 boolean preparedWrite, boolean responseNeeded,int offset, byte[] value) {if (DEBUG) Log.d(TAG, "onCharacteristicWriteRequest: preparedWrite=" + preparedWrite);
            try{mCharacteristicString = new String(value); //客户端发来的消息
            }catch(Exception e){}notifyCharacteristicWriteRequest(mCharacteristicString);
        }}@Override
    public void onCharacteristicReadRequest(BluetoothDevice device, int requestId,
                                            int offset, BluetoothGattCharacteristic characteristic) {if (DEBUG) Log.d(TAG, "onCharacteristicReadRequest()");
        notifyCharacteristicReadRequest();
    }
};

关于其他的蓝牙设备回调,接收发送数据包给蓝牙设备等操作,就要放在回调的其他几个方法了,具体都有相关的说明和标注,就不一一列出了。

五:蓝牙设备断开问题

在这里一定要说明的是,close一定要放在disconnect后调用,如果看过安卓蓝牙的底层源码的,一定有看到close中其实是有调用到disconnect方法的。很多时候设备断开后无法再重新连接,都是因为已经达到了手机蓝牙可连接设备的上限值,基本上手机可缓存的蓝牙设备都是在6个或者6个以上的,但是超过这个数量之后,就会发现始终连接不上设备的问题,类似蓝牙连接中常见的133问题,大多数时候我们在断开设备或者不需要蓝牙连接的时候,最好是调用close来回收掉BluetoothGatt,下次在重新创建一个连接对象。

mBluetoothGatt.disconnect();
mBluetoothGatt.close();
mBluetoothGatt = null;

五:关于蓝牙设备中出现的133问题

1、就是建立及时回收蓝牙连接断开方法

// 断开连接
public boolean disConnect() {if (mBluetoothGatt != null) {System.out.println("断开连接");
        Log.d("TAG", "连接失败,已断开连接" + mBluetoothGatt);
        mBluetoothGatt.disconnect();
        mBluetoothGatt.close();
        mBluetoothGatt = null;
        connect_flag = false;
        setConnectionState(BluetoothProfile.STATE_DISCONNECTED);
        cleanControl();
        return true;
    }return false;
}

2、安卓底层还有一个回收刷新蓝牙缓存的方法,不过是无法调用的。在“android.bluetooth.BluetoothGatt”

在“android.bluetooth.BluetoothGatt”类中有一个“refresh”方法是隐藏性质的方法,所以要通过java反射机制来调用此方法。

清理方法如下,一般建议放在最后清理缓存的时候调用,否则你会发现由于清理了缓存,反复都连接不上设备

/**
 * 清理蓝牙缓存
 */
public boolean refreshDeviceCache() {if (mBluetoothGatt != null) {try {Method localMethod = mBluetoothGatt.getClass().getMethod("refresh", new Class[0]);
            if (localMethod != null) {boolean bool = ((Boolean) localMethod.invoke(mBluetoothGatt, new Object[0])).booleanValue();
                return bool;
            }} catch (Exception localException) {L.i(TAG, "An exception occured while refreshing device");
        }}return false;
}

大致流程就说完了,其中还有很多坑,比如特征码注册问题了,无法正常断开设备问题了,重启蓝牙后无法正常连接设备等,以后再找时间对此单独在写一篇文章吧,另外附上gothub上发布的蓝牙设备连接搜索整的Demo地址

https://github.com/wangyetongsss/BluetoothDevice

Android蓝牙连接问题总结相关推荐

  1. android连接蓝牙耳机,蓝牙耳机厂家:Android蓝牙连接的一些心得

    蓝牙耳机厂家最近做一个项目,主要是给蓝牙发送指令的,boss要求能够最快速度的搜索到蓝牙,并且发送数据. 刚开始也遇到很多133,各种断开连接的问题.android蓝牙搜索有两种方式,一种startL ...

  2. android蓝牙连接133问题的解决办法---(连接篇)

    上一篇文章介绍了"蓝牙扫描",今天来说一下android蓝牙连接过程中133的问题: 我们经常在网上看到一些答案说需要释放gatt资源,这种方式可以在一定程度上减少出现133的概率 ...

  3. android蓝牙连接取消后怎么重新连上,重新启动后接收蓝牙连接更改

    我试图与接收器一起检查与不同设备的蓝牙连接,然后将其记录在logcat中.它适用于正常情况,但在重新启动时会失败.重新启动后接收蓝牙连接更改 这是一个正常的工作流程: 手机上 切换蓝牙开/关 重启手机 ...

  4. Android 蓝牙连接

    一.概述 蓝牙是一种无线技术标准,可实现固定设备.移动设备和楼宇个人域网之间的短距离数据交换.最多可以同时和7个其它蓝牙设备建立连接,进行通信.蓝牙可分为两大类:传统蓝牙(蓝牙3.0规范之前),低功耗 ...

  5. DCloud UniAPP Android 蓝牙连接ESCPOS打印机

    1.蓝牙打印引用文件 btprinter.js import context from "@/common/context.js" //上下文处理 用来保存绑定的蓝牙设备地址fun ...

  6. Android蓝牙连接之SPP协议

    Android蓝牙协议分为两种,SPP协议和BLE(Bluetooth low energy),Android4.3以上加入了低功耗蓝牙即BLE蓝牙协议,本篇文章我主要介绍下spp蓝牙协议的一些特性( ...

  7. Android 蓝牙连接(简单简单版)

    该博客只是记录,不会详细说明(本人技术有限不会说) 一:声明蓝牙权限和定位权限 <!--蓝牙权限--> <uses-permission android:name="and ...

  8. android 蓝牙 连接失败,Android蓝牙连接 – 服务发现失败

    我正在尝试创建一个基本的蓝牙应用程序,用于测试设备. 我从developer.android获得了代码. 这是链接: http : //developer.android.com/guide/topi ...

  9. Android蓝牙连接a2dp蓝牙耳机

    开发环境: 开发工具:Androidstudio 适配机型:honor8(Android6.0), 坚果R1(Android8.0) 开发功能:Android中蓝牙连接A2DP设备,蓝牙耳机设备 功能 ...

最新文章

  1. webpack学习(1)
  2. access violation reading 0x0000000000000020
  3. OpenCV学习(33) 轮廓的特征矩Moment
  4. 单独使用modelsim进行仿真
  5. 单元测试(二)基本使用争议篇
  6. 【渝粤题库】国家开放大学2021春2528监督学题目
  7. 在python中函数和类都属于可调用对象_在Python中函数和类都属于可调用对象
  8. Yum 安装 mysql5.7
  9. 使用Flexible实现H5页面的终端适配
  10. 浏览器本地存储(cookie、sessionStorage和localStorage)
  11. Qt UDP组播的应用
  12. AD9的PCB技巧——覆铜的规则设置
  13. history 路由 vs hash 路由 vs location.href 实现跳转
  14. RGB565,RGB555, RGB888,RGB32转换
  15. win10pe系统计算机名修改,Win10怎么修改账户名?|Win10怎么改用户名称?
  16. 彻底关闭FF新闻资讯
  17. 【逗老师带你学IT】PRTG获取HUAWEI FusionServer iBMC传感器状态
  18. Python高级编程之数据库sqlite3(一)
  19. Ubuntu 使用 du 查看某个文件夹大小
  20. 【android逆向笔记】(一)简单登录逆向

热门文章

  1. zookeeper在Hbase中的作用
  2. List 和Array 相互转化
  3. 这篇文章,把我都快看哭了...
  4. HEX飞行器:像乐高一样组装的开源飞行器
  5. 打开 XMind.exe 时出现 invalid configuration location 导致无法打开的解决方案
  6. centos sqlite3安装及简单命令
  7. Github搜索骚技巧,快速查找优质开源项目
  8. 解决安装macOS需要管理员账号和密码
  9. Python 将大量图像合成视频
  10. 《看聊天记录都学不会Python到游戏实战?太菜了吧》(5)用前朝的剑斩今朝的官