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 ...
随机推荐
- 初试linux,cp、rm、mv、file、umask等命令粗略使用方法
ls --color=never 不要依據檔案特性給予顏色顯示: --color=always 顯示顏色 --color=auto 讓系統自行依據設定來判斷是否給予顏色 --full-time 以完整 ...
- SQL模糊查询的四种匹配模式
执行数据库查询时,有完整查询和模糊查询之分,一般模糊语句如下: SELECT 字段 FROM 表 WHERE 某字段 Like 条件 一.四种匹配模式 关于条件,SQL提供了四种匹配模式: 1.% 表 ...
- 使用flask搭建微信公众号:实现签到功能
终于到了实战阶段.用微信公众号实现一个简单的签到功能. 前情提要: 微信公众号token验证失败 使用flask搭建微信公众号:完成token的验证 使用flask搭建微信公众号:接收与回复消息 程序 ...
- jquery easyui 1.3.4 datagrid pageNumber 設置導致兩次請求的解决方案
$('#table').datagrid({ url: '/get/data/path/to/your/server', pageNumber: , pageSize: , ... }); 當手動設置 ...
- VS2012 VS2010 VTK引入设置
1.C/C++ ---> 附加包含的目录 F:/VTK61/VTK-6.1.0/SLN/Filters/Sources F:/VTK61/VTK-6.1.0/VTK-6.1.0/Filters/ ...
- Spring源码窥探之:@Profile
Spring为我们提供的多环境启动 1. 配置类,注入三个不同环境的数据源,并加上注解 /** * description: 以下准备了三套不同环境的数据源 * * @author 70KG * @d ...
- make 命令出现:"make:*** No targets specified and no makefile found.Stop."
我们在Linux 安装包的时候,使用make 命令出现:"make:*** No targets specified and no makefile found.Stop."这样的 ...
- Python垃圾回收机制?
Python的GC模块主要运用了“引用计数”(reference counting)来跟踪和回收垃圾.在引用计数的基础上,还可以通过“标记-清除”(mark and sweep)解决容器对象可能产生的 ...
- Jmeter扩展自定义函数
步骤1.导入lib\ext下ApacheJMeter_core.jar和ApacheJMeter_functions.jar 步骤2.新建function的类的package声明必须已".f ...
- LeetCode 721. Accounts Merge
原题链接在这里:https://leetcode.com/problems/accounts-merge/ 题目: Given a list accounts, each element accoun ...