IOS 蓝牙
ios 蓝牙依赖CoreBluetooth 库
1 首先增加库 CoreBluetooth    general-> Linked Frameworks and lib
2 权限info.plist 申明权限,Bluetooth Peripheral Usage
需要2个后台模式,app communicates usering COreBluetooth 
app shares data using CoreBluetooth
3 库底下主要的几个类
CBCentral  CBCentralManager     中心
CBPeripheral  CBPeripheralManager  外设
CBService SBCharacteristic  CBDescriptor  CBUUID 服务 特征 描述 UUID 
4 流程:
(中心,外设,服务,特征)
-> 【中心】初始化 -> 中心扫描外设 -> 中心连接外设 
-> 【外设】搜索【服务】 
-> 【外设】搜索【服务的特征 】
-> 【外设】读特征的【特征值】
-> 【外设】发现特征的【特征描述】
-> 【外设】写数据到指定【特征】
-> 【特征】 character.properties 属性,有可读,可写,可写无返回,广播,通知等几种类型

A 初始化中心 init CBCentralManager,设置代理, 在回调  centralManagerDidUpdateState 中判断蓝牙是否可用
B 中心搜索外设centerManager  scanForPeripheralsWithServices ,在回调 didDiscoverPeripheral 中发现设备(有多个外设,回调返回多次)
C 定时几秒后调用 中心停止搜索 centerManager  stopScan
D 中心连接外设 centerManager  connectPeripheral: perip  连接其中一个外设, 在回调 didConnectPeripheral 确认已经连接上
E 已连接上的外设搜索服务  peripheral  discoverServices:   在回调 didDiscoverServices  发现服务(有多个服务,回调返回多次)
E 发现的服务对象搜索特征,service.peripheral discoverCharacteristics , 在回调 didDiscoverCharateristicsForService 发现特征
F 外设读特征 periphera readValueForCharacteristic , 在回调 didUpdateValueForCharacteristic 中获取特征值value
H 外设读特征描述 discoverDescriptorsForCharacteristic  ,在回调 didDiscoverDescriptorsForCharacteristic  发现特征描述
I 外设写特征 peripheral writeValue:data forCharacteristic:writeChara   写数据到有写属性的特征中

注意:
1 推荐IOS 蓝牙调试工具 lightBlue, 可做为中心,可建立虚拟外设
2 读写特征传递的value 是NSData 类型,注意定义好编码,lightBlue默认是 十六进制,可改为UTF-8
然后就可以自由传 中英文了
3 发现的外设,有connectable = 0的,不可连接的外设,可自行过滤
4 连接以后容易断线,再次从步骤 D connectPeripheral 即可

————————————————————————————
Android 蓝牙
1 Android 蓝牙库直接在android.jar 中,android.bluetooth 包底下
2 蓝牙权限
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
为适配安卓6.0以及以上版本需要添加一个模糊定位的权限
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
3 主要的几个类
 BluetoothAdapter   适配器,主要管理,有点类似CBCentralManager
 BluetoothDevice 设备
 BluetoothGattService 服务  BluetoothGattCharacteristic 特征 BluetoothGattDescriptor 描述
4 流程: 和IOS 类似
(一)打开蓝牙
在搜索设备之前需要询问打开手机蓝牙,其关键代码如下:
    //获取系统蓝牙适配器管理类
    private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter
            .getDefaultAdapter();
    // 询问打开蓝牙
    if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                Toast.makeText(this, "蓝牙已经开启", Toast.LENGTH_SHORT).show();
            } else if (resultCode == RESULT_CANCELED) {
                Toast.makeText(this, "没有蓝牙权限", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
(二)搜索设备
本文主要针对BLE蓝牙开发,因此采用mBluetoothAdapter.startLeScan(LeScanCallback callback)方式扫描BLE蓝牙设备。
mBluetoothAdapter.startLeScan(callback);
private LeScanCallback callback = new LeScanCallback() {
    @Override
    public void onLeScan(BluetoothDevice device, int arg1, byte[] arg2) {
        //device为扫描到的BLE设备
        if(device.getName() == "目标设备名称"){
            targetDevice = device;//获取目标设备
        }
    }
};
(四)连接设备
通过扫描BLE设备,根据设备名称区分出目标设备targetDevice,下一步实现与目标设备的连接。在连接设备之前要停止搜索蓝牙。
mBluetoothAdapter.stopLeScan(callback);
注 :停止搜索一般需要一定的时间来完成,最好调用停止搜索函数之后加以100ms的延时,保证系统能够完全停止搜索蓝牙设备。
停止搜索之后启动连接过程。
BLE蓝牙的连接方法相对简单只需调用connectGatt方法,函数原型如下:
public BluetoothGatt connectGatt (Context context, boolean autoConnect, BluetoothGattCallback callback);
返回值 BluetoothGatt: BLE蓝牙连接管理类,主要负责与设备进行通信。
boolean autoConnect:建议置为false,能够提升连接速度。
BluetoothGattCallback callback 连接回调,重要参数,BLE通信的核心部分。
(五)设备通信
与设备建立连接之后与设备通信,整个通信过程都是在BluetoothGattCallback的异步回调函数中完成。
BluetoothGattCallback中主要回调函数如下:
private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status,
                int newState) {
        }
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);
        }
        @Override
        public void onDescriptorWrite(BluetoothGatt gatt,
                BluetoothGattDescriptor descriptor, int status) {
        };
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        }
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic) {
        }
    };
(1)等待设备连接成功
当调用targetdDevice.connectGatt(context, false, gattCallback)后系统会主动发起与BLE蓝牙设备的连接,
若成功连接到设备将回调onConnectionStateChange方法,其处理过程如下:
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
                int newState) {
            if (newState == BluetoothGatt.STATE_CONNECTED) {
                Log.e(TAG, "设备连接上 开始扫描服务");
                // 开始扫描服务,安卓蓝牙开发重要步骤之一
                mBluetoothGatt.discoverServices();
            }
            if (newState == BluetoothGatt.STATE_DISCONNECTED) {
                /*连接断开后的相应处理*/      
            }
};
判断newState == BluetoothGatt.STATE_CONNECTED表明此时已经成功连接到设备。
(2)开启扫描服务
mBluetoothGatt.discoverServices();
扫描BLE设备服务是安卓系统中关于BLE蓝牙开发的重要一步,一般在设备连接成功后调用,扫描到
设备服务后回调onServicesDiscovered()函数,函数原型如下:。
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    private List<BluetoothGattService> servicesList;
    //获取服务列表
    servicesList = mBluetoothGatt.getServices();
}
BLE蓝牙协议下数据的通信方式采用BluetoothGattService、BluetoothGattCharacteristic和BluetoothGattDescriptor三个主要的类实现通信。
BluetoothGattService 服务,是构成BLE设备协议栈的组成单位,一个蓝牙设备协议栈一般由一个或者多个BluetoothGattService组成。
BluetoothGattCharacteristic 特征,一个服务包含一个或者多个特征,特征作为数据的基本单元。
一个BluetoothGattCharacteristic特征包含一个数据值和附加的关于特征的描述BluetoothGattDescriptor。
BluetoothGattDescriptor:用于描述特征的类,其同样包含一个value值。
(3)获取负责通信的BluetoothGattCharacteristic
BLE蓝牙开发主要有负责通信的BluetoothGattService完成的。当且称为通信服务。通信服务通过硬件工程师提供的UUID获取。获取方式如下:
BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString("蓝牙模块提供的负责通信UUID字符串"));
通信服务中包含负责读写的BluetoothGattCharacteristic,且分别称为notifyCharacteristic和writeCharacteristic。
其中notifyCharacteristic负责开启监听,也就是启动收数据的通道,writeCharacteristic负责写入数据。
具体操作方式如下:
  BluetoothGattService service = mBluetoothGatt.getService(UUID.fromString("蓝牙模块提供的负责通信服务UUID字符串"));
   // 例如形式如:49535343-fe7d-4ae5-8fa9-9fafd205e455
  notifyCharacteristic = service.getCharacteristic(UUID.fromString("notify uuid"));
  writeCharacteristic =  service.getCharacteristic(UUID.fromString("write uuid"));
(4)开启监听
开启监听,即建立与设备的通信的首发数据通道,BLE开发中只有当上位机成功开启监听后才能与下位机收发数据。开启监听的方式如下:
mBluetoothGatt.setCharacteristicNotification(notifyCharacteristic, true)
BluetoothGattDescriptor descriptor = characteristic
                            .getDescriptor(UUID
                                    .fromString
("00002902-0000-1000-8000-00805f9b34fb"));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
若开启监听成功则会回调BluetoothGattCallback中的onDescriptorWrite()方法,处理方式如下:
@Override
public void onDescriptorWrite(BluetoothGatt gatt,
                BluetoothGattDescriptor descriptor, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            //开启监听成功,可以像设备写入命令了
            Log.e(TAG, "开启监听成功");
        }   
};
(5)写入数据
监听成功后通过向 writeCharacteristic写入数据实现与下位机的通信。写入方式如下:
//value为上位机向下位机发送的指令
writeCharacteristic.setValue(value);
mBluetoothGatt.writeCharacteristic(writeCharacteristic)
其中:value一般为Hex格式指令,其内容由设备通信的蓝牙通信协议规定。(改为UTF-8)
(6)接收数据
若写入指令成功则回调BluetoothGattCallback中的onCharacteristicWrite()方法,说明将数据已经发送给下位机。
@Override
public void onCharacteristicWrite(BluetoothGatt gatt,
            BluetoothGattCharacteristic characteristic, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.e(TAG, "发送成功");
            }   
            super.onCharacteristicWrite(gatt, characteristic, status);
}
若发送的数据符合通信协议,则下位机会向上位机回复相应的数据。发送的数据通过回调onCharacteristicChanged()方法获取,其处理方式如下:
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic) {
            // value为设备发送的数据,根据数据协议进行解析
            byte[] value = characteristic.getValue();
}

通过向下位机发送指令获取下位机的回复数据,即可完成与设备的通信过程。
(六)断开连接
当与设备完成通信之后之后一定要断开与设备的连接。调用以下方法断开与设备的连接:
mBluetoothGatt.disconnect();
mBluetoothGatt.close();

有几个库对Android蓝牙做了封装
https://github.com/dingjikerbo/Android-BluetoothKit
https://github.com/moruoyiming/BlueUtils
https://github.com/a-voyager/BluetoothHelper

Andorid/IOS 蓝牙开发总结相关推荐

  1. iOS蓝牙开发---CoreBluetooth[BLE 4.0] 初级篇[内附Demo地址]

    一.蓝牙基础知识 (一)常见简称 1.MFI  make for ipad ,iphone, itouch 专们为苹果设备制作的设备,开发使用ExternalAccessory 框架(认证流程貌似挺复 ...

  2. iOS 蓝牙开发 BabyBluetooth蓝牙库介绍

    BabyBluetooth 是一个最简单易用的蓝牙库,基于CoreBluetooth的封装,并兼容iOS和Mac OS X. 特色: 基于原生CoreBluetooth框架封装的轻量级的开源库,可以帮 ...

  3. iOS 蓝牙开发资料记录

    一.蓝牙基础认识:   1.iOS蓝牙开发:   iOS蓝牙开发:蓝牙连接和数据读写   iOS蓝牙后台运行  iOS关于app连接已配对设备的问题(ancs协议的锅)          iOS蓝牙空 ...

  4. iOS蓝牙开发:蓝牙连接和数据读写

    当下蓝牙开发可谓是越来越火,不论是智能穿戴的兴起还是蓝牙家具,车联网蓝牙等等,很多同学也会接触到蓝牙的项目,我从事蓝牙开发也有一段时间了,经手了两个项目.废话不多说了,先向大家简单的介绍有关蓝牙开发的 ...

  5. ios 蓝牙开发总结

    随着蓝牙低功耗技术BLE(Bluetooth Low Energy)的发展,蓝牙技术正在一步步成熟,如今的大部分移动设备都配备有蓝牙4.0,相比之前的蓝牙技术耗电量大大降低.从iOS的发展史也不难看出 ...

  6. iOS蓝牙开发数据实时传输

    随着iOS项目开发  很多app需要通过蓝牙与设备连接 蓝牙开发注意: 先定义中心设备和外围设备以及遵守蓝牙协议 @interface ViewController()<CBCentralMan ...

  7. iOS蓝牙开发:蓝牙的连接和数据的读写

    蓝牙开发说简单也简单,说不简单也有点难,开发人员在首次开发蓝牙前首先需要搞清楚蓝牙开发的概念,还要了解掌握蓝牙开发的一整套流程,这样才能快速上手开发蓝牙. 蓝牙开发分为两种模式:管理者模式和中心者模式 ...

  8. iOS蓝牙开发连接系统或其他APP已经连接、配对成功的蓝牙设备

    在蓝牙开发的时候,扫描外设的方法扫描到的设备只能是没有被连接的设备,也就是说如果有设备在本手机中已经连接配对成功了之后就不会被 [_centralManager scanForPeripheralsW ...

  9. iOS蓝牙开发 --- 唯一标识问题

    需求: 当我们使用CoreBluetooth系统框架进行蓝牙开发的时候,有时因为某种功能需求需要拿到特定的蓝牙设备进行特定的操作,这就需要我们拿到能够代表特定的蓝牙设备的唯一标识,通过唯一标识来确认是 ...

最新文章

  1. Paper9:Fast RCNN
  2. 无序列表属性 隐藏方式 JS简介
  3. Navicat中查询哪些表有指定的字段名(技巧)
  4. hadoop使用lzo压缩文件笔记
  5. 文件逆序改为正序脚本
  6. 断言、触发器、存储过程
  7. 【LeetCode笔记】152. 乘积最大子数组(Java、动态规划)
  8. linux resin 服务功能,linux服务之resin
  9. python内置数据类型与特点_初学Python之内置数据类型一
  10. 智能机器人语音识别技术
  11. 洛谷P3749 [六省联考2017]寿司餐厅
  12. BZOJ 1677. [Usaco2005 Jan]Sumsets 求和
  13. html5 查询展示页面,基于Html5的可视化展示页面自动发布方法及系统与流程
  14. VC++2010安装教程
  15. 关于融资融券和转融通
  16. 【全套完结】电磁场与电磁波实验-----全套Matlab仿真实验
  17. 清明时节雨纷纷,心思却剪不断,理还乱
  18. 递归最小二乘(RLS)算法详解
  19. 2D前景触发与3D触发结合案例
  20. 超级计算机 人脑,迄今为止没有一部超级计算机的综合能力超过人脑

热门文章

  1. VBA教程初级(六):动态声明数组
  2. 游戏客户端之cocostudio的动画库
  3. CVPR 2018,盘点我心中的创意 TOP10
  4. Red Hat 7完全卸载MySQL
  5. 一、可行性分析研究报告-模板
  6. ASP.NET:Repeater 留言板
  7. 三星s20 android 10.0,三星S20+真机上手,接近真全面屏,可以和Note10+说再见了...
  8. 基于MATLAB的汽车出入库计时计费车牌识别系统
  9. 不是吧,不是吧,这年头还有人不知道算法的重要性?我进字节年薪45w+全靠大佬这份笔记!
  10. Spring initializr总是网络连接超时?赶紧来看看解决办法吧