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 coding style guide 的快速落地实践——业内python 编码风格就pep8和谷歌可以认作标准
python coding style guide 的快速落地实践 机器和人各有所长,如coding style检查这种可自动化的工作理应交给机器去完成,故发此文帮助你在几分钟内实现coding st ...
- Product Oriented Recurrence(Codeforces Round #566 (Div. 2)E+矩阵快速幂+欧拉降幂)
传送门 题目 \[ \begin{aligned} &f_n=c^{2*n-6}f_{n-1}f_{n-2}f_{n-3}&\\ \end{aligned} \] 思路 我们通过迭代发 ...
- poj1860 Currency Exchange(spfa判断是否存在正环)
题意:有m个货币交换点,每个点只能有两种货币的互相交换,且要给佣金,给定一开始的货币类型和货币数量,问若干次交换后能否让钱增加. 思路:spfa求最长路,判断是否存在正环,如果存在则钱可以在环中一直增 ...
- python字符的表示格式
%% 百分号标记 #就是输出一个% %c 字符及其ASCII码%s 字符串%d 有符号整数(十进制)%u 无符号整数(十进制)%o 无符号整数(八进制)%x 无符号整数(十六进制)%X 无符号整数(十 ...
- 珠峰 - 郭永峰react课程 node es6 babel学习笔记
npm install babel-cli -g //安装babel babel index.js -o a.js //等同于 babel index.js --out-file a.js 复制ind ...
- MyBatis框架-ResultMap节点
需求:查询结果要求显示用户名,用户密码,用户的角色 因为在用户表中只有用户角色码值,没有对应的名称,角色名称是在码表smbms_role表中,这时我们就需要联表查询了. 之前我们使用的是给查询结果字段 ...
- Learning Vector Quantization
学习矢量量化. k近邻的缺点是你需要维持整个数据集的训练. 学习矢量量化算法(简称LVQ)是一种人工神经网络算法,它允许你选择要挂在多少个训练实例上,并精确地了解这些实例应该是什么样子. LVQ的表示 ...
- LeetCode 742. Closest Leaf in a Binary Tree
原题链接在这里:https://leetcode.com/problems/closest-leaf-in-a-binary-tree/ 题目: Given a binary tree where e ...
- cube.js 学习 cube docker-compose 运行
cube.js 官方为我们也提供了backeng 部署的模型,为了测试方便以下是一个使用docker-compose 运行的demo 项目是一个集成gitbase 的demo,实际可以按照自己的项目修 ...
- CSS块元素、行内元素、行内块元素的转换
一.块元素转行内元素:display:inline 二.行内元素转块元素:display:block div{ display: inline; /*无效 width: 500px; height: ...