Android蓝牙4.0的数据通讯

  我在两家公司都用到了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!");}}


       

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/419392.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

荐 Intellij IDEA创建Maven Web项目(带有webapp文件夹目录的项目)

转载自&#xff1a;点击打开链接 在创建项目中&#xff0c;IDEA提供了很多项目模板&#xff0c;比如Spring MVC模板&#xff0c;可以直接创建一个基于Maven的Spring MVC的demo&#xff0c;各种配置都已经设定好了&#xff0c;直接编译部署就可以使用。 最开始自己创建maven we…

iOS设计模式 - 迭代器

iOS设计模式 - 迭代器 原理图 说明 提供一种方法顺序访问一个聚合对象中的各种元素&#xff0c;而又不暴露该对象的内部表示。 源码 https://github.com/YouXianMing/iOS-Design-Patterns // // Node.h // IteratorPattern // // Created by YouXianMing on 15/10/26. // …

Android程序杀死自己的进程和其他程序进程方法

1.获取程序进程ID&#xff1b; int pidandroid.os.Process.myPid(); android.os.Process..killProcess(pid); 2.杀死其他程序进程&#xff1b; ActivityManager manager(ActivityManager)getSystemService(ACTIVITY_SERVICE); manager.killBackgroundProcesses("packa…

maven依赖关系中Scope的作用

Dependency Scope 在POM 4中&#xff0c;<dependency>中还引入了<scope>&#xff0c;它主要管理依赖的部署。目前<scope>可以使用5个值&#xff1a; * compile&#xff0c;缺省值&#xff0c;适用于所有阶段&#xff0c;会随着项目一起发布。 * provided&…

如何运行ruby代码

第一种&#xff0c;ruby -e 在命令行中运行下面命令&#xff0c;-e的意思是&#xff0c;把后面的字符串当作脚本执行 ruby -e "print hello" 使用irb交互控制台 在命令行输入irb hello worldxingooxingoo-Lenovo:~/workspace/RubyTest$ irb irb(main):001:0> p &q…

使用ViewPager制作Android引导界面

1.涉及Android知识点&#xff1a; ViewPager组件、Handler机制、SharedPreferences。 2.开发实践&#xff1a; a.布局文件设计。 第一个引导界面one.xml&#xff0c;另外两个布局文件类似。 <?xml version"1.0" encoding"utf-8"?> <LinearLay…

6、控件样式模板和使用

WPF控件模板 潜移默化学会WPF(样式篇)---改造CheckBox&#xff0c;全新metro风格 WPF CheckBox 自定义样式 继续聊WPF控件——自定义CheckBox控件外观 用WPF自定义CheckBox的样式 [wpf教程-自定义样式的checkbox开关控件 http://www_suchso.com/projecteactual/wpf-jiaocheng-c…

Android 蓝牙4.0在实际开发中的运用

1.蓝牙搜索. 首先是获取BluetoothAdapter对象&#xff1a; final BluetoothManager bluetoothManager (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); BluetoothAdapter bluetoothAdapter bluetoothManager.getAdapter(); 当blueto…

Mysql递归查询,无限级上下级菜单

mysql递归查询&#xff0c;mysql中从子类ID查询所有父类&#xff08;做无限分类经常用到&#xff09; 由于mysql 不支持类似 oracle with ...connect的 递归查询语法 之前一直以为类似的查询要么用存储过程要么只能用程序写递归查询. 现在发现原来一条sql语句也是可以搞定的 先…

“睡服”面试官系列第二篇之promise(建议收藏学习)

目录 1promise的定义 2基本用法 3. Promise.prototype.then() 4. Promise.prototype.catch() 5. Promise.all() 6. Promise.race() 7. Promise.resolve() 8. Promise.reject() 9. 两个有用的附加方法 10总结 1promise的定义 Promise 是异步编程的一种解决方案&#xf…

Android M 新的运行时权限开发者需要知道的一切

android M 的名字官方刚发布不久&#xff0c;最终正式版即将来临&#xff01; android在不断发展&#xff0c;最近的更新 M 非常不同&#xff0c;一些主要的变化例如运行时权限将有颠覆性影响。惊讶的是android社区鲜有谈论这事儿&#xff0c;尽管这事很重要或许在不远的将来会…

查看IIS连接数

如果要想知道确切的当前网站IIS连接数的话&#xff0c;最有效的方法是通过windows自带的系统监视器来查看。 一、运行-->输入“perfmon.msc”. 二、在“系统监视器”图表区域里点击右键&#xff0c;然后点“添加计数器”. 三、在“添加计数器”窗口&#xff0c;“性能对象”…

SpringMVC关于json、xml自动转换的原理研究[附带源码分析]

目录 前言现象源码分析实例讲解关于配置总结参考资料 前言 SpringMVC是目前主流的Web MVC框架之一。 如果有同学对它不熟悉&#xff0c;那么请参考它的入门blog&#xff1a;http://www.cnblogs.com/fangjian0423/p/springMVC-introduction.html 现象 本文使用的demo基于maven…

“睡服”面试官系列第三篇之变量的结构赋值(建议收藏学习)

目录 变量的解构赋值 1. 数组的解构赋值 2. 对象的解构赋值 3. 字符串的解构赋值 4. 数值和布尔值的解构赋值 5. 函数参数的解构赋值 6. 圆括号问题 7. 用途 变量的解构赋值 1. 数组的解构赋值 基本用法 ES6 允许按照一定模式&#xff0c;从数组和对象中提取值&#…

【宋红康程序思想学习日记3】杨辉三角

class Shuzu3 { public static void main(String[] args) {    int[][] yanghuinew int[10][];   //初始化二维数组   for(int i0;i<yanghui.length;i){     yanghui[i]new int[i1]; }   for(int i0;i<yanghui.length;i){     for(int j0;j<yanghui…

Android为网络请求自定义加载动画

android自带的加载动画都不怎么好看&#xff0c;在这里介绍一种自定义加载动画的方法 原始图片&#xff1a; 编写动画progressbar.xml, <?xml version"1.0" encoding"utf-8"?> <animated-rotate android:drawable"drawable/publicloading&…

mybatis在xml文件中处理大于号小于号的方法

第一种方法&#xff1a; 用了转义字符把>和<替换掉&#xff0c;然后就没有问题了。 SELECT * FROM test WHERE 1 1 AND start_date < CURRENT_DATE AND end_date > CURRENT_DATE 附&#xff1a;XML转义字符 < …