10分钟完成一个最最简单的BLE蓝牙接收数据的DEMO
这两天在研究蓝牙,网上有关蓝牙的内容非常有限,Github上的蓝牙框架也很少很复杂,为此我特地写了一个最最简单的DEMO,实现BLE蓝牙接收数据的问题,
不需要什么特定的UUID,
不需要什么断开重连,
不需要什么多连接等等,
网上都把BLE蓝牙写的好复杂好复杂,那不是我想要的,我只想为新手提供一个最基本的例子
注意:
1.本DEMO运行前提是蓝牙已经配对成功,如果想实现自动配对可以期待我的下一篇文章
2.修改代码中的“你想要接收数据的已配对设备名称”为你真实的蓝牙设备
3.复制粘贴下面的代码,日志TAG是“BLE”
代码:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast; import java.util.List;
import java.util.Set;
import java.util.UUID; public class MainActivity extends AppCompatActivity {
private BluetoothAdapter adapter;
private BluetoothGatt bluetoothGatt; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openBlueToothLe();
} //打开蓝牙
private void openBlueToothLe() {
adapter = BluetoothAdapter.getDefaultAdapter();
if (null == adapter) {
Toast.makeText(this, "没有蓝牙功能", Toast.LENGTH_SHORT).show();
return;
}
if (!adapter.isEnabled()) {
adapter.enable();
}
startScan();
} //开始扫描
private void startScan() {
Set<BluetoothDevice> bondedDevices = adapter.getBondedDevices();
for (BluetoothDevice bondedDevice : bondedDevices) {
if ("你想要接收数据的已配对设备名称".equals(bondedDevice.getName().trim())) {
connectDevice(bondedDevice);
}
}
} //连接设备
private void connectDevice(BluetoothDevice bondedDevice) {
bluetoothGatt = bondedDevice.connectGatt(this, false, new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
if (BluetoothGatt.STATE_CONNECTED == newState) {
bluetoothGatt = gatt;
gatt.discoverServices();
} else if (BluetoothGatt.STATE_DISCONNECTED == newState) {
gatt.close();
}
} @Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
List<BluetoothGattService> services = gatt.getServices();
for (BluetoothGattService service : services) {
List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
for (BluetoothGattCharacteristic character : characteristics) {
enableNotification(gatt, service.getUuid(), character.getUuid());
}
}
} @Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
byte[] value = characteristic.getValue();
Log.i("BLE", "receive value ----------------------------");
for (int i = 0; i < value.length; i++) {
Log.i("BLE", "character_value = " + value[i]);
}
}
});
} @Override
protected void onDestroy() {
super.onDestroy();
bluetoothGatt.disconnect();
} public boolean enableNotification(BluetoothGatt gatt, UUID serviceUUID, UUID characteristicUUID) {
boolean success = false;
BluetoothGattService service = gatt.getService(serviceUUID);
if (service != null) {
BluetoothGattCharacteristic characteristic = findNotifyCharacteristic(service, characteristicUUID);
if (characteristic != null) {
success = gatt.setCharacteristicNotification(characteristic, true);
if (success) {
// 来源:http://stackoverflow.com/questions/38045294/oncharacteristicchanged-not-called-with-ble
for (BluetoothGattDescriptor dp : characteristic.getDescriptors()) {
if (dp != null) {
if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
dp.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
} else if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) {
dp.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
}
gatt.writeDescriptor(dp);
}
}
}
}
}
return success;
} private BluetoothGattCharacteristic findNotifyCharacteristic(BluetoothGattService service, UUID characteristicUUID) {
BluetoothGattCharacteristic characteristic = null;
List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
for (BluetoothGattCharacteristic c : characteristics) {
if ((c.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0
&& characteristicUUID.equals(c.getUuid())) {
characteristic = c;
break;
}
}
if (characteristic != null)
return characteristic;
for (BluetoothGattCharacteristic c : characteristics) {
if ((c.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0
&& characteristicUUID.equals(c.getUuid())) {
characteristic = c;
break;
}
}
return characteristic;
}
}
对,就是这么简单,一个类足以,接下来就可以在Android studio的Logcat看到打印的返回值了
Github地址:https://github.com/king1039/BlueToothLe
欢迎关注我的微信公众号:安卓圈
10分钟完成一个最最简单的BLE蓝牙接收数据的DEMO的更多相关文章
- CBrother脚本10分钟写一个拯救“小霸王服务器”的程序
CBrother脚本语言10分钟写一个拯救“小霸王服务器”的程序 到了一家新公司,接手了一坨c++服务器代码,到处内存泄漏,这服务器没有数据库,挂了后重启一下就好了,公司就这么凑活着用了几年了,定时重 ...
- Django从Models 10分钟定制一个Admin后台
目录 Django从Models 10分钟建立一套RestfulApi Django从Models 10分钟定制一个Admin后台 简介 Django自带一个Admin后台, 支持用户创建,权限配置和 ...
- 10 分钟实现一个自己的server监控器
需求 近期须要给自己的server加入监控器.目的是监控server的内存.CPU.磁盘占用率,资源占用率过高的话能给自己发个提醒.当前主流的平台通常会提供邮件.短息.甚至会提供微信提醒,只是这类提醒 ...
- 10分钟搭建一个小型网页(python django)(hello world!)
10分钟搭建一个小型网页(python django)(hello world!) 1.安装django pip install django 安装成功后,在Scripts目录下存在django-ad ...
- Android5.0(Lollipop) BLE蓝牙4.0+浅析demo连接(三)
作者:Bgwan链接:https://zhuanlan.zhihu.com/p/23363591来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. Android5.0(L ...
- python scrapy 入门,10分钟完成一个爬虫
在TensorFlow热起来之前,很多人学习python的原因是因为想写爬虫.的确,有着丰富第三方库的python很适合干这种工作. Scrapy是一个易学易用的爬虫框架,尽管因为互联网多变的复杂性仍 ...
- android5.0 BLE 蓝牙4.0+浅析demo搜索(一)
作者:Bgwan链接:https://zhuanlan.zhihu.com/p/23341414来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. 作者:Bgwan 莳萝花 ...
- Java工作流引擎结合可视化表单开发,10分钟完成一个业务流程发布
回忆以前工作流引擎的应用,感觉历历在目啊!当初公司接了一个项目关于政府单位公文流转的管理系统,一开始客户跟我画了十多张业务流程图.话说这十多张业务流程图,涉及的业务范围还蛮多,像用审批授权,开通流程, ...
- 10分钟写一个markdown编辑器
marked.js Marked是一个Markdown解析引擎. vue.js Vue.js(读音 /vjuː/, 类似于 view) 是一套构建用户界面的 渐进式框架.与其他重量级框架不同的是,Vu ...
随机推荐
- 用python+openpyxl从表格中读取测试用例的多条数据,然后将执行结果写入表格中
# -*- coding: utf-8 -*- from selenium import webdriver from openpyxl import load_workbook class mylo ...
- 趣味编程:FizzBuzz(Haskell版)
g :: Int -> Int -> Int -> String g n 0 0 = "FizzBuzz" g n 0 _ = "Fizz" ...
- 简易配置中心Confd入手
改成动态更新配置文件,如下每五秒重新生成配置文件 confd与etcd的使用 Add keys This guide assumes you have a working etcd, or consu ...
- solidworks 学习 (四)
旋钮三维建模
- git log filter(六)
显示前10条提交记录: root@vmuer-VirtualBox:/media/vmuer/share/cmake-uart-server# git log -10 commit b056dacb0 ...
- 正确创建本地C++发布构建PDBS
在调试版本中遇到的一个问题是编译本地的C++应用程序.例如,许多局部变量消失了,因为代码生成器没有将它们放在堆栈上,而是将它们放在寄存器中,就像在调试生成中发生的那样.此外,release积极地构建对 ...
- 抓取Dump文件的方法和工具介绍
一.Windows系统的任务管理器里抓dump 启动任务管理器,选中某个进程,右键,弹出菜单"创建转储文件" 注意事项: 当你在64位Windows系统上抓32位进程的dmup文件 ...
- tomcat 配置更改 web 目录
tomcat 虚拟目录:( 编辑 tomcat/conf/server.xml ) <Host name="localhost" appBase="webapps ...
- Android中创建自定义控件
1.创建一个TitleLayout继承LinearLayout: //创建自定义控件 public class TitleLayout extends LinearLayout { private f ...
- 软件工程第二次作业——Java学习路线
我的第二次软工作业 过去我对自己所学和想学都很迷茫,以至于学得总是一知半解,但现在我想主攻Java方向,并坚定不移地走下去(之后拓展其他方面就是以后的事情了).之所以想主攻Java方向是因为Java本 ...