简体   繁体   English

我该如何管理Android中的蓝牙连接?

[英]How should I manage Bluetooth connections in Android?

Q. What are your best practices in managing bluetooth connectivity? 问: 管理蓝牙连接的最佳做法是什么?

I've read the android bluetooth guide & many bluetooth connectivity tutorials. 我已经阅读了android蓝牙指南和许多蓝牙连接教程。 Not helpful with encapsulation-design nor best practices. 对封装设计和最佳实践没有帮助。

  • When should I open/close the connection? 我应该何时打开/关闭连接?
  • Is the "connection" with a single bluetooth device called a "socket" connection? 与单个蓝牙设备的“连接”是否称为“套接字”连接?
  • Can a single connection send data while listening? 单个连接可以在收听时发送数据吗? (...or between listening states). (......或听力状态之间)。

I've never coded connectivity with external devices before. 我以前从未编译过与外部设备的连接 It took two weeks for me to wrap my head around the code that scans for near-by bluetooth devices and throw them into a ListView. 我用了两个星期的时间来绕过扫描附近蓝牙设备的代码并将它们扔进ListView。 Listeners, Broadcasts, and Adapters! 听众,广播和适配器!

My project will be printing 1-40 receipts every 15 minutes on a bluetooth receipt printer. 我的项目将在蓝牙收据打印机上每15分钟打印1-40张收据。 At the moment, security is not an issue. 目前,安全性不是问题。 On the same connection, it will also be receiving data (sending & receiving simultaneously does not appear to be necessary but would be useful). 在同一个连接上,它也将接收数据(同时发送和接收似乎不是必要的,但会很有用)。 I'm not yet sure how the devices are configured on this single dongle device but I would guess the devices are connected via USB controller to the dongle. 我还不确定如何在这个单个加密狗设备上配置设备,但我猜这些设备是通过USB控制器连接到加密狗的。

So far, I have 1 object to manage a single I/O connection. 到目前为止,我有一个对象来管理单个I / O连接。 Staticly I open an activity to select a connection (to later save the label , mac , and pin in the database). 静态地我打开一个活动来选择一个连接(以后在数据库中保存标签macpin )。 Based on tutorials, I have "open", "listen", "send", and "close" methods. 根据教程,我有“打开”,“收听”,“发送”和“关闭”方法。 What confuses me is "how" to use these functions. 令我困惑的是“如何”使用这些功能。 Can I leave a connection open all day (10hrs) and use it every 3mins? 我可以整天打开连接(10小时)并每隔3分钟使用一次吗? Should I open/close the connection when sending or requesting data? 我应该在发送或请求数据时打开/关闭连接吗? Where would I detect the need to reconnect? 我在哪里可以检测到需要重新连接?

sorry for the short answer, but from my practice with the Bluetooth API, I have found that this video describe the things very good (totally personal opinion...) 对不起简短的回答,但是从我使用蓝牙API的练习中,我发现这个视频描述的东西非常好(完全是个人意见......)

Video 1 视频1

In addition this is useful when you do NOT have any previous experience 此外,如果您没有任何以前的经验,这将非常有用

Tutorial 教程

And as last check out this question in stackoverflow it has a bunch of good references and examples!! 最后在stackoverflow中查看这个问题它有一堆很好的参考和例子!

Again sorry for the shortage, but I believe that if you check these out at least most of your questions and concerns will become answered! 再次为这次短缺感到抱歉,但我相信,如果你检查这些,至少大多数问题和疑虑都会得到解答!

:) :)


EDIT 编辑


So, let me be a bit more descriptive and share some of my experience. 所以,让我更具描述性并分享我的一些经验。

I have written an App that communicates with BLE device that has 3 functions 我编写了一个与具有3个功能的BLE设备通信的应用程序

  • double sided event driven button (push the button on phone -> event is fired to the device; push the button on the BLE device -> event is fired to the phone) 双面事件驱动按钮(按下电话上的按钮 - >事件被触发到设备;按下BLE设备上的按钮 - >事件被触发到手机)

  • send request from phone -> BLE device answers with current battery percentage 从手机发送请求 - > BLE设备以当前电池百分比回答

  • continuously reading strength signal (as aprox. distance) between the phone and the BLE device 持续读取手机和BLE设备之间的强度信号(为aprox。距离)


So far so good, now the things is that the basic approach is: 到目前为止一切顺利,现在事情是基本的方法是:

  1. Search for BLE devices (bluetooth search or "discovery" of nearby bluetooth devices) 搜索BLE设备(蓝牙搜索或附近蓝牙设备的“发现”)

    • Here you will need android permissions! 在这里你需要android权限!
  2. Choose the device you want to connect to 选择要连接的设备

    • To differ the devices (maybe there are a lot around you :) ) you can use BLE device's name or UUID or ... best - use the name ;) 不同的设备(可能你周围有很多:))你可以使用BLE设备的名称或UUID或...最好 - 使用名称;)
  3. After both devices connect to each other you can then start the Gatt communication. 在两个设备相互连接后,您可以启动Gatt通信。 The approach with state machine is a little too much overkill for me. 使用状态机的方法对我来说有点太过分了。 But anyway the communication is done through bytes (in my case...) 但无论如何,通信是通过字节完成的(在我的情况下......)

  4. In one of the videos/resources there was something specific and VERY HELPFUL at least for me! 在其中一个视频/资源中,至少对我来说有一些特定的,非常有用的! To be honest I don't remember it exactly, but the idea was that before any communication it's RECOMMENDED to read/get all the options from the BLE device or something similar... 说实话,我并不完全记得它,但想法是在任何通信之前,建议阅读/获取BLE设备的所有选项或类似的东西......

    • Maybe it was something like discoverOptions() or something like that 也许它就像discoverOptions()之类的东西
  5. Great thing will be to know your device "communication codes" or at least I call them that way. 伟大的事情将是知道你的设备“通信代码”或至少我这样称呼他们。

    • Check this link for example: Link ** Now you can see there are tables with the USEFUL INFO! 检查此链接,例如: 链接 **现在您可以看到有表有可用的信息! Eg if you want to read the battery level you navigate to this page and find that in order to read the battery, the service name is UUID XXXXX and you need to send 0x01 to the BLE device and it will "answer" to your call with some data which is again in bytes. 例如,如果您想要读取电池电量,请导航到此页面并查找为了读取电池,服务名称为UUID XXXXX,您需要将0x01发送到BLE设备,它将“回答”您的呼叫一些数据再次以字节为单位。

I really hope that this is somehow helpful! 我真的希望这在某种程度上有所帮助!

PLEASE NOTE This is strictly coming from my experience and there could be some mismatches or wrong terms, but that's how I personally see the things and because my project was long ago, I don't remember most of the things exactly. 请注意 这完全来自我的经验,可能存在一些不匹配或错误的术语,但这就是我个人看到的东西,因为我的项目很久以前,我不记得大部分事情。

IMPORTANT: 重要:

This is only a summery of STUCI's provided links above. 这只是上面提供的STUCI提供的链接的总结。 He has since updated his answer and I have not updated/edited this summery. 他已经更新了他的答案, 我没有更新/编辑这个夏季。 Topics in my summery are not explanatory but provided for reference and help in generating specific questions. 我的夏季主题不是解释性的,而是提供参考和帮助产生具体问题。

Original Post... 原帖...

Thank you Stuci! 谢谢Stuci! Some of that was helpful:- some not. 其中一些是有帮助的: - 有些不是。 I thought it best to collect my thoughts and see what has been explained and if anything hasn't. 我认为最好收集我的想法,看看有什么解释,如果没有。

(I can't post this much in a comment tho, sorry) (我不能在评论中发布这么多,抱歉)

PLEASE CALL ME ON ANYTHING THAT IS INCORRECT. 请打电话给我任何不正确的事情。

Video of Bluetooth LE 蓝牙LE的视频

(Covers a bunch of random things) (涵盖一堆随机的东西)

While I "dont-like" videos of code:- I watched it because it was recommended ... and I am glad I did. 虽然我“不喜欢”代码视频: - 我看了它,因为它被推荐......我很高兴我做到了。 While not very helpful it did introduce some concepts I was unaware of. 虽然不是很有帮助但它确实引入了一些我不知道的概念。 Since I am targeting old android devices (v8+) the LE features are inconsequential. 由于我的目标是旧的Android设备(v8 +),因此LE功能无关紧要。

  • Pushing Data: [Depending on the source feature-set], one does not need to continually pull data (ex. with a temperature sensor) but some devices can "push" it to the device on change. 推送数据:[根据源功能设置],不需要连续提取数据(例如使用温度传感器),但有些设备可以在更改时将其“推”到设备上。 Seems to use the 'advertisement" design concept. 似乎使用'广告'设计概念。
  • UUIDs define Services and/or Characteristics of the connected device. UUID定义连接设备的服务和/或特性。
  • Possibility to write configuration on (to) connected devices. 可以在(连接)设备上写入配置。
  • Characteristics which seem to be simply "settings" that can be assigned over bluetooth. 看似简单的“设置”的特征可以通过蓝牙分配。 Not sure if this (~19mins) applies to non-gatt connectoins but seems similar to the state-machine that controls 不确定这个(~19分钟)是否适用于非gatt连接,但看起来类似于控制的状态机
  • Advertisements which seem to be the "metadata" regarding the devices current state or config (~24mins). 似乎是关于设备当前状态或配置(~24分钟)的“元数据”的广告。 Again, not sure if this even applies to non LE Bluetooth. 再次,不确定这是否适用于非LE蓝牙。

Leaving Connections Open 保持连接打开

Bluetooth connections can indeed remain open; 蓝牙连接确实可以保持开放; starting at the point which the "startActivityForResult(...) method is successfully called. Two basic things affect whether or not one would want to maintain an open connection: 从成功调用“startActivityForResult(...)方法的那一点开始。两个基本的因素会影响是否要维护一个打开的连接:

  1. Understand the power consumption. 了解功耗。
    • Having the adapter active simply consumes additional power. 使适配器处于活动状态只会消耗额外的电量。 If one can keep the adapter shut-off while it is not "absolutely-needed" will mearly save battery power. 如果可以在不“绝对需要”的情况下保持适配器关闭,则可以节省电池电量。
  2. Accidental disconnects are managed. 管理意外断开连接。
    • Other than leaving the connection continually connected, one could disconnect & reconnect regularly at specified intervals to ensure a connection is up. 除了连接连接之外,还可以按指定的时间间隔断开连接并重新连接,以确保连接正常。
    • In the thread(s) used for I/O, one could check for a disconnect and reconnect (possibly starting a new thread). 在用于I / O的线程中,可以检查断开连接并重新连接(可能启动新线程)。

I/O Streams pr Connection I / O Streams连接

A single connection can indeed "have" simultaneous Input & Output streams. 单个连接确实可以“拥有”同时的输入和输出流。 I 一世

Since it was suggested, I re-read Android's Bluetooth Guide and under "managing a connection" (talking about a single socket) I noticed this... 既然有人建议,我重新阅读Android的蓝牙指南并在“管理连接”(谈论单个插座)下我注意到了......

  1. Get the InputStream and OutputStream that handle transmissions through the socket, via getInputStream() and getOutputStream(), respectively. 获取分别通过getInputStream()和getOutputStream()处理通过套接字传输的InputStream和OutputStream。
  2. Read and write data to the streams with read(byte[]) and write(byte[]). 使用read(byte [])和write(byte [])读取和写入数据流。

...but continues with noting that read & write block each other. ...但继续注意到读写会相互阻塞。 Something I still need to look further into. 我仍需要进一步研究的东西。 It seems like you cant I/O simultaneously on the same socket??? 好像你不能同时在同一个插槽上进行I / O ???

Max Connections 最大连接数

I also looked into the max connection issue Stuci added and found no documentation on the Android-side. 我还查看了Stuci添加的最大连接问题,并且在Android端没有找到任何文档。 It might exist, I cant find it. 它可能存在,我找不到它。 However, most people seem to agree that there is a limitation (that could be as low as 4) imposed by whatever hardware you are coding for. 但是,大多数人似乎都同意,无论您编写什么硬件,都存在限制(可能低至4)。 Some notable links: - How many devices we can pair via Bluetooth of BLE to Android? 一些值得注意的链接: - 我们可以通过BLE蓝牙与Android配对多少台设备? - How many maximum device can we pair via Bluetooth to android device at a time? - 我们一次可以通过蓝牙与Android设备配对多少台设备? - https://groups.google.com/forum/#!topic/android-developers/adeBD275u30 - https://groups.google.com/forum/#!topic/android-developers/adeBD275u30

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM