我在两家公司都用到了app与BLE设备通讯,当时也是什么都不懂,在网上各种搜索,各种查资料,总算弄出来了。在这里记录下来,希望对有需要的人有些帮助。

  1.检测手机是否支持蓝牙4.0(一般手机4.3以上的android系统都支持)

<span style="font-size:14px;"> if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {showMsg(R.string.ble_not_supported);finish();}</span>

   2.检测蓝牙是否打开,提示用户打开蓝牙(在此之前需要加相应的权限)
      添加权限:

<span style="font-size:14px;">    <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/><uses-permission android:name="android.permission.BLUETOOTH"/><uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/></span>

获取蓝牙适配器

   <span style="font-size:14px;">final BluetoothManager bluetoothManager =(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);bluetoothAdapter = bluetoothManager.getAdapter();
如果蓝牙处于关闭状态,则通过下面代码提示用户启动蓝牙:
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
</span>

3.启动关闭蓝牙,获取蓝牙状态

判断蓝牙状态:bluetoothAdapter.isEnabled()

开启蓝牙:bluetoothAdapter.enable();

关闭蓝牙:bluetoothAdapter.disable();

 

      4.蓝牙启动后,就该搜索设备了

开启搜索: bluetoothAdapter.startLeScan(mLeScanCallback);

停止搜索: bluetoothAdapter.stopLeScan(mLeScanCallback);

搜索回调:

          private BluetoothAdapter.LeScanCallback mLeScanCallback =new BluetoothAdapter.LeScanCallback() {@Overridepublic void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {runOnUiThread(new Runnable() {@Overridepublic void run() {//在这里将搜到的设备显示到界面}});}};

5.建立连接

          public boolean connect(BluetoothDevice  device ) {if (device == null) {Log.w(TAG, "Device not found.  Unable to connect.");return false;}mBluetoothGatt = device.connectGatt(this, false, mGattCallback);return true;}

连接时需要注册一个回调接口:

    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {//检测连接状态变化
@Overridepublic void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {if (newState == BluetoothProfile.STATE_CONNECTED) {} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {}}@Overridepublic void onServicesDiscovered(BluetoothGatt gatt, int status) {}@Overridepublic void onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic,int status) {}//接收蓝牙回传数据@Overridepublic void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic) {System.out.println("接收数据");byte[] data=characteristic.getValue();}//检测用户向蓝牙写数据的状态@Overridepublic void onCharacteristicWrite(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic, int status) {Log.e(TAG, "write status"+":"+status);if(status==BluetoothGatt.GATT_SUCCESS){System.out.println("--------write success----- status:");}super.onCharacteristicWrite(gatt, characteristic, status);}};

断开连接:

mBluetoothGatt.disconnect();

 6.发送数据

//设置特性数据回传通知

  public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,boolean enabled) {if (mBluetoothAdapter == null || mBluetoothGatt == null) {Log.w(TAG, "BluetoothAdapter not initialized");return;}if (mBluetoothGatt.setCharacteristicNotification(characteristic, enabled)) {BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);mBluetoothGatt.writeDescriptor(descriptor);}}/*** 向设备发送数据* @param serviceUuid* @param characterUuid* @param notifactionUuid* @param data*/public void writeDataToDevice(byte[] data){if (mBluetoothGatt == null) {return;}BluetoothGattService bluetoothGattService = mBluetoothGatt.getService(UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb"));//蓝牙设备中需要使用的服务的UUIDif (bluetoothGattService == null) {Log.e(TAG, "service:"+mBluetoothGatt.getServices().size());Log.e(TAG, "service not found!");return;}BluetoothGattCharacteristic mCharac = bluetoothGattService.getCharacteristic("0000fff6-0000-1000-8000-00805f9b34fb");//需要使用该服务下具体某个特性的UUIDif (mCharac == null) {Log.e(TAG, "HEART RATE Copntrol Point charateristic not found!");return;}BluetoothGattCharacteristic nCharacteristic=bluetoothGattService.getCharacteristic("0000fff7-0000-1000-8000-00805f9b34fb");//蓝牙模块向手机端回传特性UUIDsetCharacteristicNotification(nCharacteristic, true);Log.e(TAG, "data:"+Arrays.toString(data));mCharac.setValue(data); //设置需要发送的数据try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}writeCharacteristic(mCharac);}public void writeCharacteristic(BluetoothGattCharacteristic characteristic) {if (mBluetoothAdapter == null || mBluetoothGatt == null) {Log.e(TAG, "BluetoothAdapter not initialized");return;}boolean result=mBluetoothGatt.writeCharacteristic(characteristic);//开始写入数据if(result){Log.e(TAG, "write success!");}else {Log.e(TAG, "write fail!");}}

Android蓝牙4.0的数据通讯相关推荐

  1. android蓝牙4.0 BLE低功耗应用

    转自    http://www.cnblogs.com/zdz8207/archive/2012/10/17/bluetooth_ble_android.html 谈谈几个月以来开发android蓝 ...

  2. 谈谈几个月以来开发android蓝牙4.0 BLE低功耗应用的感受

    谈谈几个月以来开发android蓝牙4.0 BLE低功耗应用的感受 谈谈几个月以来开发android蓝牙4.0 BLE低功耗应用的感受,注明下时间:2012-10-17写的博客,后期更新的也注明了时间 ...

  3. ym——物联网入口之中的一个Android蓝牙4.0

    转载请注明本文出自Cym的博客(http://blog.csdn.net/cym492224103),谢谢支持! 假设还有同学不知道蓝牙4.0能够做什么请查看Android+蓝牙 4.0 将带来什么? ...

  4. ym——物联网入口之一Android蓝牙4.0

    转载请注明本文出自Cym的博客(http://blog.csdn.net/cym492224103),谢谢支持! 如果还有同学不知道蓝牙4.0可以做什么请查看Android+蓝牙 4.0 将带来什么? ...

  5. 开发android蓝牙4.0 BLE低功耗应用的感受

    文章转自: http://www.cnblogs.com/zdz8207/archive/2012/10/17/bluetooth_ble_android.html 谈谈几个月以来开发android蓝 ...

  6. Android 蓝牙4.0(BLE)Demo

    给大家分享一下蓝牙4.0的Demo,本篇介绍基本使用 最终效果 如何获取UUID 使用 Android 蓝牙4.0(BLE) Demo下载 最终效果 如何获取UUID 去手机华为应用市场下载一个叫蓝牙 ...

  7. 一款强大的芯片nRF52840及利用蓝牙5.0实现数据远程采集

    一.nRF52840蓝牙芯片简介 自从nordic在2018年强势推出nRF52840这颗重磅级芯片后,蓝牙5.0技术开始在业界流行起来,随后蓝牙5.0技术开始成为了各大品牌的旗舰手机标配功能. 1. ...

  8. Android蓝牙4.0 BLE开发坑总结

    onServicesDiscovered 回调里不能直接执行 write /readDataFromCharacteristic() 或者 enableNotificationOfCharacteri ...

  9. android 蓝牙4.0(BLE) 开发

    简介 蓝牙发展至今经历了9个版本的更新.1.1.1.2.2.0.2.1.3.0.4.0.4.1.4.2.5.0.那么在1.x~3.0之间的我们称之为传统蓝牙,4.x开始的蓝牙我们称之为低功耗蓝牙也就是 ...

最新文章

  1. 【Python基础】使用统计函数绘制简单图形
  2. centos7下搭建git和gitlab版本库
  3. 拖着3个箱子,跨越太平洋,求学美帝 那一年我19岁
  4. python中str isupper_python pandas Series.str.isupper用法及代码示例
  5. centos 查找nginx_centos7 nginx安装/启动/进程状态/杀掉进程
  6. 基于爬山算法求解TSP问题(JAVA实现)
  7. Auty 2017——WebMonitor接口本地检测平台
  8. c 语言读取注册表信息,C++读取注册表的实现方法
  9. c语言爱心代码空心,c语言心形图案代码,是什么?
  10. selenium和python的关系,Selenium+python
  11. STM32工作笔记0091---ADC模数转换实验-M3
  12. mysql8.0.15安装方法 mysql8安装教程
  13. 关于写程序时「对数据库操作」的一些总结。
  14. python画3d图-python3利用Axes3D库画3D模型图
  15. 【转】 sqlserver 异地备份
  16. 动态提出的数据怎么换行 js_前端代码动态生成应用及改造
  17. cat 查看文件内容,默认输出到屏幕
  18. 转载:Linux内核探索之路——关于书
  19. 启明星Exchange/outlook预定会议室终端显示解决方案
  20. 啦啦外卖43.5学习研究开发

热门文章

  1. 前端学习(653):算数运算符
  2. 前端学习(625):数据类型导读
  3. 前端学习(545):node的系统模块require
  4. 第六十五期:IBM净利润下降38%,旧时代巨头如何自救?
  5. 实例54:python
  6. windbg linux内核调试,windbg调试虚拟机XP系统
  7. Matrix PKU 2155
  8. 个人的博客搭建(持续更新)
  9. 学习基础和C语言基础调查
  10. Python map/reduce