Android 中线程或服务中的蓝牙通信?

发布于 2024-10-04 07:01:30 字数 205 浏览 4 评论 0原文

我正在开发涉及蓝牙通信的应用程序。即使建立连接的活动关闭,蓝牙通信也应该继续。首先,我想到使用服务来实现此目的,这似乎是正确的方法。但是,在蓝牙聊天示例中,通信发生在另一个线程中,而不是在服务中。我已经在我的应用程序中使用了该代码并且它工作正常。使用线程进行蓝牙通信是否正确,还是我只需要使用服务?蓝牙通信应该处于活动状态,直到我的应用程序位于 RAM 中,并且如果我在活动之间切换应该没有关系。

I am developing app which has bluetooth communication involved. The bluetooth communication should go on even if the Activity that sets up the connection closes down. First, I have thought of using Service for this and that seemed to be right way. But, in Bluetooth chat example the communication happens in another thread and not in Service. I have used that code in my app and its working properly. Is using Thread for bluetooth communication proper or do I need to make use of Service only? The bluetooth communication should be active till my app is in RAM and it should not matter if I switch between activities.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

杀お生予夺 2024-10-11 07:01:30

好吧,在您的情况下,单独的线程与服务没有什么不同,只是它遵循 Android 的活动生命周期,但线程可能会被终止,并且无法恢复任何状态。一旦服务被终止,Android 将尝试重新启动该服务。

Well a seperated Thread is not differnd then a service in you case, except that it follows the activity life cycle of Android, but a Thread might be killed and no state can be recovered. Android will try to restarted a service once it was killed.

躲猫猫 2024-10-11 07:01:30

回答你的问题有点晚了,但我想迟总比不好。
我曾经开发过一个在两个设备之间进行蓝牙通信的应用程序,我想总结一下我的经验。
当我们想要执行一些不是很繁重的后台进程时,我们通常使用的服务,在某种程度上,我的意思是该服务(如果它很大)会阻塞我的主 UI 线程,从而减慢您的操作系统或 ANR 可能,这是我们不想要什么。

蓝牙通信是一个不断运行的进程,应该仅使用线程来完成,因为它将作为单独的线程工作,并且不会对主 UI 线程产生任何影响。
如果我错了,请纠正我。

A little too late to answer your query, but better late than never I suppose.
I have worked on an application that has the bluetooth communication between two devices and I would like to summarize my experience.
A service we use normally when we want do some background process that is not very heavy, in a way, I mean the service (if it is huge) will block my main UI thread hence slowing down your OS or ANR may be, which is what we don't want.

The bluetooth communcation is an ever running process which should be done using a Thread only as this will work as a separate thread and wont have any impact on the main UI thread.
Please correct me if I am wrong.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文